Hot questions for Using Android EditText in user interface

Question:

I was googling for a while but I can't find the way how to add a another EditText after I click on one.

I try to describe my problem by this picture:

Is there a some container providing this functionality ?


Answer:

You can add all 5 to your XML and assign android:visibility="gone" to all but first one. You then need to assign a TextWatcher to each one off them, but for the simplicity I will only show it for one.

et1.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                et2.setVisibility(TextUtils.isEmpty(s.toString()) ? View.GONE : View.VISIBLE);
                // The rest of them also???
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

If you do not want a fixed number of them, you will want to programmatically create EditTexts and then adding them to one of the ViewGroups (RelativeLayout, LinearLayout, FrameLayout, ...) by calling addView method

Question:

I've noticed that in an edittext if you type one (or several) letter/s and then do a double space it replaces the first space with a period - it obviously thinks that you're trying to enter a new sentence. I want to disable this behavior - how is this possible?

<EditText
            android:id="@+id/someId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginEnd="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:hint="@string/somehint"
            android:textColorHint="@color/somecolor"
            android:textSize="20sp"
            android:textColor="@android:color/black"
            android:background="@android:color/white"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:cursorVisible="true"
            android:textCursorDrawable="@null"
            />

Answer:

This is a setting of the keyboard, not your app. You can find it under

Settings > Language & input > Keyboard & input methods > (your keyboard)

As far as I am aware, it cannot be disabled. Your best bet may be to look into input method styles https://developer.android.com/training/keyboard-input/style.html

Question:

I am working on an Android application in which I want to add EditText below an EditText which is at the first added in XML, and then added in code one below the other. Even though I am giving margin from top 200, the new EditText is appearing on top right. What am I doing wrong?

XML file:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border"
    android:orientation="horizontal"

    >

    <RelativeLayout
        android:id="@+id/menuLayout"
        android:layout_width="wrap_content"
        android:layout_height="1000dp">

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="180dp"
            android:background="@drawable/bottom_border"
            android:padding="3dp"
            android:scaleType="fitXY"
            android:src="@drawable/mittag_top" />

        <EditText
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="80dp"
            android:layout_marginStart="80dp"
            android:layout_marginTop="125dp"
            android:hint="Menu karte datum..."
            android:lineSpacingExtra="10dp"
            android:lineSpacingMultiplier="1"
            android:paddingTop="7dp"
            android:textColor="@color/abc_primary_text_material_dark"
            android:textColorHint="@color/abc_primary_text_material_dark"
            android:textSize="12sp" />

        <EditText
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:layout_alignLeft="@+id/menuDate"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignStart="@+id/menuDate"
            android:layout_below="@+id/menuDate"
            android:hint="Opening times..."
            android:lineSpacingExtra="10dp"
            android:lineSpacingMultiplier="1"
            android:paddingTop="7dp"
            android:textColor="@color/abc_primary_text_material_dark"
            android:textColorHint="@color/abc_primary_text_material_dark"
            android:textSize="12sp" />

        <EditText
            android:id="@+id/firstEntry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/openTime"
            android:textColor="@color/abc_primary_text_material_dark"
            android:textColorHint="@color/abc_primary_text_material_dark"
            android:hint="Menu entry.." />
    </RelativeLayout>
</ScrollView>

Java code :

public class AddStuff extends Activity{

    EditText firstEntry, date, time;
    RelativeLayout relativeLayout;
    Typeface type;
    int counter = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ocr_menu);


        type = Typeface.createFromAsset(getAssets(),"fonts/MyFont.ttf");
        firstEntry = (EditText)findViewById(R.id.firstEntry);
        firstEntry.setTypeface(type);
        date = (EditText)findViewById(R.id.date);
        date.setTypeface(type);
        time = (EditText)findViewById(R.id.time);
        time.setTypeface(type);
        relativeLayout = (RelativeLayout)findViewById(R.id.menuLayout);

        firstEntry.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    addEditText();
                }
            }
        });

    }

    public void addEditText(){
        EditText editText = new EditText(getApplicationContext());
        editText.setHint("Entry number "+counter);
       // editText.setPadding(2, 200, 2, 2);
        TableLayout.LayoutParams params = new TableLayout.LayoutParams();
        params.setMargins(2, 300, 0, 0);
        editText.setHintTextColor(Color.WHITE);
        editText.setTypeface(type);
        relativeLayout.addView(editText);
        counter++;
    }
}

What am I doing wrong? How can I add EditText below the last added EditText. Thank you.

Update

updated addEdittext()

public void addEditText(){
        EditText editText = new EditText(getApplicationContext());
        editText.setHint("Entry number "+counter);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        int idLastChild= relativeLayout.getChildAt(relativeLayout.getChildCount()-1).getId();
        params.addRule(RelativeLayout.BELOW,idLastChild);
        editText.setHintTextColor(Color.WHITE);
        editText.setTypeface(type);
        relativeLayout.addView(editText);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 5) {
                    addEditText();
                }
            }
        });
        counter++;
    }

Answer:

Because adding dynamic EditText in RelativeLayout so need to use LayoutParams .addRule instead of margin to align EditText:

    EditText editText = new EditText(AddStuff.this);
    ... 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                                  RelativeLayout.LayoutParams.MATCH_PARENT, 
                                       RelativeLayout.LayoutParams.WRAP_CONTENT);

// get last child id from RelativeLayout
 int idLastChild=relativeLayout.getChildAt(relativeLayout.getChildCount()-1);
 params.addRule(RelativeLayout.BELOW,idLastChild);
  // set id for EditText 
 editText.setId(idLastChild+1);
 // set layout params
 editText.setLayoutParams(params);
 relativeLayout.addView(editText, params);

Question:

I'm getting an error with my following code implementation.

Math cannot be applied to android.widget.EditText

Then, I googled for the issue and found a link Math with an integer obtained from an EditText. I tried to edit related codes. However, I'm yet to solve my issue.

This is my UI for respective class activity. Where you can see, that I will choose respective models from the spinner and the giving 4 different inputs.

Next is some parts of my code:

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String tDistance = distanceEdit.getText().toString();
        String freqStr = freqEdit.getText().toString();
        String tBase = tHeightEdit.getText().toString();
        String rMobile = rHeightEdit.getText().toString();
        double distance = Double.parseDouble(!tDistance.isEmpty() ? tDistance : "0");
        double frequency = Double.parseDouble(!freqStr.isEmpty() ? freqStr : "0");
        //double frequency = Double.parseDouble(freqStr);
        double baseHeight = Double.parseDouble(!tBase.isEmpty() ? tBase : "0");
        double mobileHeight = Double.parseDouble(!rMobile.isEmpty() ? rMobile : "0");



        if(v == calButton) {
            //String freqStr = freqEdit.getText().toString();

            if(freqStr != null && !freqStr.isEmpty()) {
                mResult=69.55+26.16*Math.log(frequency)-13.82*Math.log(baseHeight)-antennaFac+(44.9-6.55*Math.log(baseHeight))*Math.log(distance);

            }
        } else
        if(v == clearButton) {
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                               long arg3) {
        // TODO Auto-generated method stub
        switch(arg2) {
            case 0:
                antennaFac = (1.1*Math.log(freqEdit)-0.7)*rHeightEdit-(1.56*Math.log(freqEdit)-0.8);//Error from freqEdit - Math cannot be applied to android.widget.EditText
//Error when trying to use frequency variable - Unable to resolve symbol
                    break;
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
            }
        }

My problem is currently in the onItemSelected method where my freqEdit parameter shows the error I highlighted above. To my own understanding, it was supposed to be frequency variable which has already been declared in the OnClick method. However, it says that "cannot resolve symbol 'frequency'"


Answer:

You have declared your frequencyvariable inside your onClickfunction, and the onItemSelectedis in a completely different scope.

Declare ´frequency´ as a member class and update its value in onClick as you are already doing, then you will be able to use it in your onItemSelected method.

Hope it helps

EDIT

You can also recalculate your frequency value in your onClick method executing the following statements again.

String freqStr = freqEdit.getText().toString();
double frequency = Double.parseDouble(!freqStr.isEmpty() ? freqStr : "0");

Question:

So I have an EditText, (two actually, but both have the same problem,) and I added an OnTouchListener. I need to know what EditText I'm working with for another method. The problem is, before adding the listener, if I clicked somewhere in the EditText, the cursor would update. Now the cursor won't update at all.

 editText.setOnTouchListener(new View.OnTouchListener() {
        @SuppressWarnings("UnusedAssignment")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            EditText et = (EditText) v;
            et.requestFocus();
            return true;
        }
    });

Answer:

In this case, it is best to return false in onTouch. This is because the return value specifies whether or not the listener consumes the event. Returning false should therefore allow the widget to respond to the touch event with its normal behaviour, in addition to whatever else you have specified.

Question:

I use an EditText to filter some values in an ListView.

It works so far, but I have one problem. First my code:

final EditText mEditText = (EditText) this.findViewById(R.id.filterEditText);
mEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

    @Override
    public void afterTextChanged(Editable editable) {
        String mFilter = editable.toString();
        mListViewUpdater.setFilter(mFilter);
        Log.d("Editable", editable.toString());
    }
}

The method afterTextChanged() gets called when I type something in and the filter is applied and works.

But if I delete everything in the EditText, the ListView stays at it last filtered state until I close the keyboard and then it shows all values again.

Is there a way to show all values eevn if the EditText is empty but the Keyboard is not collapsed?

Best regards!


Answer:

Put all of your code into the onTextChanged() method instead of the afterTextChanged() method.