Hot questions for Using Android EditText in focus

Question:

I have 2 EditText (myEditText1 and myEditText2) And I need when touch myEditText1 1. Do some business [No problem here and required business applied] 2. Then request focus to myEditText2 [ No luck? ]

final EditText myEditText1 = (EditText) findViewById(R.id.myEditText1);
final EditText myEditText2 = (EditText) findViewById(R.id.myEditText2);

// ...

myEditText1.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        // My business when myEditText1 touched [ OK ]
        // ...

        // TODO
        // Need to request focus to another EditText myEditText2 ?

        return false;
    }
});

I try some solutions like following trials But no luck and focusing still on myEditText1

myEditText2.requestFocus();

Related questions EditText request focus Change Focus to EditText Android


Answer:

You can set an OnClickListener on your edit text like this:

this.editText1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //your code
                editText2.requestFocus();
            }
});

Just take care about a special case onClick() is not called when the EditText doesn't have focus And you can find details of this case in the following question thread onClick event is not triggering | Android

Question:

My app contains a popup with an EditText. I want the user to be able not to only type and delete text, but to also copy & paste from and to the EditText box.

After searching online I found that the following xml tag should do the trick.

android:textIsSelectable="true"

I added the line but then I can't open the keyboard by clicking on the EditText box.

I found many solutions that open the keyboard explicitly but that isn't what I'm looking for, I want it to open on a click and to allow copying and pasting text with a long click, just like an EditText in the browser, for example.

Adding one of the following doesn't work as well:

<requestFocus />

edit_text.requestFocus();

xml:

        <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true"
        android:text=""
        android:textSize="25sp"
        android:gravity="center_horizontal"
        android:inputType="text"
        android:layout_weight="0.1"
        android:id="@+id/editTextPopup_input"
        android:layout_marginEnd="20sp" />

Java:

    public static void inflateEditTextPopup(int parent_id, String content_text, String edit_text_text, String act_button_text)
{
    LayoutInflater layoutInflater = (LayoutInflater)Main.main_activity.getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
    final View popupView = layoutInflater.inflate(R.layout.edit_text_popup, null);
    final PopupWindow window = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    window.setFocusable(true);
    final EditText input = (EditText)popupView.findViewById(R.id.editTextPopup_input);
    input.setText(edit_text_text);
    input.setFocusable(true);
    input.requestFocus();

    TextView content = (TextView)popupView.findViewById(R.id.editTextPopup_content);
    content.setText(content_text);

    Button btnClose = (Button)popupView.findViewById(R.id.editTextPopup_cancel);
    btnClose.setOnClickListener(new Button.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            window.dismiss();
        }
    });

    Button btnAct = (Button)popupView.findViewById(R.id.editTextPopup_ok);
    btnAct.setText(act_button_text);
    btnAct.setOnClickListener(new Button.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            handleEditTextPopupInput(window, input.getText().toString());
            window.dismiss();
        }
    });

    LinearLayout parent = (LinearLayout)Main.main_activity.findViewById(parent_id);
    window.showAsDropDown(parent);
}

logcat:

W/TextView: TextView does not support text selection. Selection cancelled.

Answer:

After a lot of searching online I found that there is no answer, because this is a bug in Android, an EditText is not selectable from a PopupWindow.

In my case I used something like a "Paste" button, which is not very comfortable, but good enough for me.

Question:

I create some edittexts with a hashmap depending on a value given by the user. I can't do it in the xml because they doesn't exist before.

for (i = 0; i < n; i++) {
    layoutValueClassic.addView(edittextStatsList.get(i));
    edittextStatsList.get(i).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
    edittextStatsList.get(i).setGravity(Gravity.CENTER);
    edittextStatsList.get(i).setEms(2);
    edittextStatsList.get(i).setTextColor(Color.parseColor("#ffffff"));
    edittextStatsList.get(i).setBackgroundResource(R.drawable.edit_value);

    //FOCUS SUR L'EDITTEXT SUIVANT SAUF SI C'EST LE DERNIER
    edittextStatsList.get(i).setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT && i < n - 1) {
                edittextStatsList.get(i + 1).requestFocus();
                return true;
            }
            return false;
        }
    });

 }

As you can see, I put a requestfocus for each edittext on the next (i+1). But it doesn't work. I can't do "next" when I am in the edittext, I can just do "OK" and the focus disappears.

Any idea?


Answer:

set IME OPTIONS for each edittext in the loop

for (i = 0; i < n; i++) {
...
edittextStatsList.get(i).setImeOptions(EditorInfo.IME_ACTION_NEXT);
....
}

Question:

I have multiple EditText in Android XML view, which contains a sequence of "nextFocusForward" for focusing to the next EditText for inputs from keyboard, now I have a condition in which some EditText is disabled now, the sequence of the EditText focus from keyboard next is blocking anywhere, is there any way we can go to the next input if the requesting focus EditText is disabled ?


Answer:

In your condition when you set an EditText as disabled, set it also to not focusable. This way, the EditText will be ignored and the next one will be focused.

editText.setFocusable(false);

Remember to set it to true if you enable it again!

Question:

I have two EditText fields in my android app. When input is invalid in the first field, an alert dialog is triggered and I try to switch focus and the input cursor back to the EditText field (RollId) that was invalid so it can be re-entered.

The focus change and input cursor actually appears to have worked, but when I start entering input again, it all show up in the wrong editText (Location) field.

final EditText RollId = findViewById(R.id.scan_roll_id);
final EditText Location = findViewById(R.id.scan_location);

RollId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (!hasFocus) {
            if (validate.ValidateRollId(String.valueOf(RollId.getText()))) {
                // TODO: parse and populate labels
            } else {
                  // Not a valid RollId format
                  AlertDialog alertDialog = new AlertDialog.Builder(MoveMaterialActivity.this).create();
                  validate.RollIdAlert("The scanned Roll Id has the incorrect format. Please enter manually.", alertDialog);
                  TextKeyListener.clear(RollId.getText());
                  RollId.setSelection(0);
                  Location.clearFocus();
                  RollId.requestFocus();
           }
       }
   }
});

I guess I am basically trying to figure out how to block the input from Location EditText field, or switch it to the RollId EditText field. I thought RollId.setSelection(0) would achieve this.

edit: RollIdAlert())

public void RollIdAlert(String message, AlertDialog alert) {
    alert.setTitle("RollId Format Invalid");
    alert.setMessage(message);
    alert.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alert.show();
}

Answer:

Modify your validate.RollIdAlert() method to include a 3d parameter: EditText et In your listener for the closing of the alert dialog, after dismiss();, put these lines:

          et.requestFocus();
          et.setSelection(0);

Question:

I have an activity that contains 3 EditText fields. I originally wrote the code thinking that they must be performed in set order. However I have since learned they can either that user can either scan location Barcode of a product or touch the 2nd edittext and scan a UPC barcode. I am doing a re-write of project that was originally written in VB.net. My struggle is trying to control the focus of which editText has focus for input from scanner. My first version has a public void listener on scanner. I would check if the first edittext has a value and if true then I would know that the scan result goes to 2nd edittext.

I have spent several hours on onTouchListeners with no luck. My question is how can I set which edittext should get result of scan. I know how to ensure that the first field is default but how can I change focus to second editText when that field gets touched. I also don't want default android keyboard to display.


Answer:

// Set result from barcode in firstEditText

Then -

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

    }

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

    }

    @Override
    public void afterTextChanged(Editable s){
        secondEditText.requestFocus();

    }
});

Similarly addTextChangedListener on secondEditText and requestFocus() on thirdEditText.

Question:

I Am Making A Note Saver Application, For The Main Body of Note I Am Using A Multiline EditText Looks Like This:- Screenshot

Code For EditText:-

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <com.mnotes.view.TextField
        android:id="@+id/mNoteEditText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@null"
        android:gravity="top|start"
        android:inputType="textMultiLine"
        android:overScrollMode="always"
        android:scrollbarStyle="insideInset"
        android:scrollbars="vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:scrollHorizontally="false"
        android:hint="Start Writing For Here...."
        android:padding="8dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif-smallcaps"
        android:longClickable="true"
        android:textIsSelectable="true"/>
    </LinearLayout>

When I Scroll This EditText It Gains Focus Which Makes Softkey Popup, This Behaviour Makes The Scrolling Experience Very Bad.So I Want To Disable Focus On EditText While Scrolling, Please Help.


Answer:

I found a solution (only works on short texts). You can use the ScrollView onScrollChange event. This is how I did it:

ScrollView scroll = findViewById(R.id.scrollView1);
    scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View view, int i, int i1, int i2, int i3) {
            et.clearFocus();
        }
    });

The variable et is an EditText object.

Question:

When you click the back button, the keyboard hides itself but the focus on the edittext remains. How can I reproduce this behaviour?


Answer:

You can use this code to hide the keyboard:

getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);

Or this one :

View view = this.getCurrentFocus();
if (view != null) {  
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

If the EditText loses the focus, simple write a simple command

editText.requestFocus();

Question:

I call the function to open the dialog. Dialog boxes have two EditText. When I open the dialog box, the keyboard automatically pops up. How can I disable this behavior? I only need to open the keyboard when the EditText receives a touch event.


Answer:

on your onCreate() method

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

If you want all your activity use soft keyboard use this in your manifest file for your all activities

<activity
    android:configChanges="keyboardHidden|orientation"
    android:windowSoftInputMode="stateHidden" />

Question:

I have an EditText with some preinstalled text. When EditText was created, I want to select all text and the positioning at the beginning of the text. But selectAll() always transfers scrollPosition to the end.

EditText edt;
edt.requestFocus();
edt.selectAll();
edt.scrollTo(0,0); //not scrolling

Answer:

Refer this example:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter name"
        android:inputType="textCapSentences|textNoSuggestions|textMultiLine" />

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Description"
        android:inputType="textCapSentences|textNoSuggestions|textMultiLine"
        android:maxLines="6"
        android:minLines="3" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Clickhandle"
        android:text="Click" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText=findViewById(R.id.etEmail);
       // editText.setSelectAllOnFocus(true); --> Select all text inside EditText when it gets focus
    }

    public void Clickhandle(View view) {
        editText.requestFocus();
        editText.selectAll();
        editText.post(new Runnable() {
            public void run() {
                editText.scrollTo(0, 0);
            }
        });
    }
}

Question:

How can I enlarge edittext when being focussed and back to default when unfoccused. (like google chrome url field)

The edittext is @+id/edittext

Here is my code: --custom_actionbar--

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edittext"
        android:hint="@string/url"
        android:inputType="text|textNoSuggestions"
        android:imeOptions="flagNoExtractUi|actionSend"
        android:selectAllOnFocus="true"
        android:background="#ffe0e0e0"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/imageButton"
        android:layout_toStartOf="@+id/imageButton"
        android:padding="4dp" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@null"
        android:src="@drawable/ic_action_refresh"
        android:layout_centerVertical="true" />

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/edittext"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/imageButton"
        android:layout_toStartOf="@+id/imageButton" />

</RelativeLayout>

Answer:

Get reference to your edit text in your activity and apply focus listener :

Define NORMAL and LARGE as two text sizes

edit_Text = (EditText) findViewById(R.id.edittext);
edit_Text.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus){
           this.setTextSize(LARGE);
    }else {
           this.setTextSize(NORMAL);
    }
   }
});