user3383301 user3383301 - 24 days ago 9
Android Question

Android Forms : Get focused text field id

I have two Text fields .And i have focus on the first text field. If i click on an button i should be able to find which text field has focus and want to know its id.

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="33dp"
android:hint= "@string/rfid_plh"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="33dp"
android:hint= "@string/rfid1_plh"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />


How to achieve this ??

Answer

This will do it for you:

    final EditText et1,et2;
    Button checkButton;

    //initilize both edit text and button here

    checkButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(et1.hasFocus()){
                //TODO code here for edit text 1
                int id = et1.getId();
            }else if(et2.hasFocus()){
                //TODO code here for edit text 2
                int id = et2.getId();

            }
        }
    });
Comments