52

I have a number of EditText elements in my page along with two buttons. I want the user to touch on any one EditText field and click any button to insert a certain value into that very EditText field they touched. Giving input using the keypad is not allowed. Please help me to do this.

Jasperan
  • 2,154
  • 1
  • 16
  • 40
Eclipse-fan
  • 597
  • 1
  • 5
  • 11

10 Answers10

67

You can use View.OnFocusChangeListener to detect if any view (edittext) gained or lost focus.

for (EditText view : editList){
   view.setOnFocusChangeListener(focusListener);
}
....
private OnFocusChangeListener focusListener = new OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus){
             focusedView = v;
        } else {
             focusedView  = null;
        }
    }
}

This goes in your activity or fragment or wherever you have the EditTexts. The .... is just saying that you can put it anywhere else in the class. And obviously you would need to create an array with them in it, thus the editList.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Mr.Me
  • 9,192
  • 5
  • 39
  • 51
  • did u tried this code? if one of the inputs lost the focus and some other get it then listener will be called twice. can the focusedView be null after that? – Vasilii Suricov Sep 21 '17 at 14:15
42

This works for me. It returns a boolean.

myEditText.hasFocus()
Lilylakshi
  • 736
  • 7
  • 19
28

One thing that you can do is declare a global variable evalue which will tell you which is the last selected EditText by using onTouchListener and then based on the value of evalue, you can set the text value to the edittext by button click. hope you understood.

the code for it can be as follow:

EditText e1,e2;
    Button b1,b2;
    String evalue;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        e1=(EditText)findViewById(R.id.editText1);
        e2=(EditText)findViewById(R.id.editText2);
        b1=(Button)findViewById(R.id.button1);
        b2=(Button)findViewById(R.id.button2);

        e1.setOnTouchListener(new View.OnTouchListener()
        {
            public boolean onTouch(View arg0, MotionEvent arg1)
            {
                evalue="1";
                return false;
            }
        });

        e2.setOnTouchListener(new View.OnTouchListener()
        {
            public boolean onTouch(View arg0, MotionEvent arg1)
            {
                evalue="2";
                return false;
            }
        });
        b1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0) {
                if(evalue=="1")
                {
                    e1.setText("yes");
                }
                if(evalue=="2")
                {
                    e2.setText("yes");
                }
            }
        });


        b2.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0) {
                if(evalue=="1")
                {
                    e1.setText("No");
                }
                if(evalue=="2")
                {
                    e2.setText("No");
                }
            }
        });

    }

Its a logical coding.. not upto the mark.. if you find a better one. then use it. thank you.

Ankit Dhadse
  • 1,566
  • 1
  • 15
  • 19
  • Thanks a lot. This completely fulfilled my requirement. – Eclipse-fan Jun 28 '13 at 10:49
  • 5
    I think you've nailed it. There are so many other answers that assume onFocusChange is the required listener event. I think they do this because they're thinking in terms of a PC/Browser experience. This appears in-correct. Touch devices do not work like this. The problem is that when I test those other answers, the cursor is still "blinking" in the field after I touch a button. So, this means the focus is still in the field despite contacting another UI element on the screen. Therefore you have to detect what else has been touched, not whether the field is in focus. +1 – angryITguy Jul 27 '14 at 07:01
  • 3
    // The onFocusChange event will work when moving between editable fields. The trick is trying to undertstand the context of behavour on touch devices with virtual keyboards. – angryITguy Jul 27 '14 at 07:10
  • @SrujanBarai--maybe [this](https://stackoverflow.com/a/21578580/2737933) will help. – DSlomer64 Sep 01 '17 at 13:30
10

This worked for me.

e1 = (EditText) findViewById(R.id.editText1);

e1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
   @Override
   public void onFocusChange(View arg0, boolean hasfocus) {
      if (hasfocus) {
         Log.e("TAG", "e1 focused") 
      } else {
         Log.e("TAG", "e1 not focused") 
      }            
   }
});
Philip Herbert
  • 4,599
  • 2
  • 37
  • 40
10

With Java 8 lambdas:

EditText editTextTo = findViewById(R.id.editTextTo);

editTextTo.setOnFocusChangeListener((view, b) -> {
    if (view.isFocused()) {
        // Do whatever you want when the EditText is focused 
        // Example:
        editTextFrom.setText("Focused!");
    }
});

Note that the view inside the lambda function is actually an instance of an EditText.

olmedocr
  • 198
  • 3
  • 12
8

Have your Fragment implement OnTouchListener & OnFocusChangeListener:

public class AttributesFragment extends Fragment 
                       implements OnTouchListener, OnFocusChangeListener {

Then implement using:

@Override
public boolean onTouch(View view, MotionEvent event) {
    if (view instanceof EditText) {
        view.setOnFocusChangeListener(this); // User touched edittext
    }
    return false;
}

@Override
public void onFocusChange(View v, boolean hasFocus) {

}

Don't forget to set your listener after creating your EditText

editText.setOnTouchListener(this);

This way if an EditText box is focused by default but user has not changed the field it will not fire the onFocusChange event.

Siddhivinayak
  • 1,103
  • 1
  • 15
  • 26
dwp4ge
  • 1,963
  • 22
  • 27
  • 1
    This is the best answer. I like the fact that you catered for focus events that are not triggered by direct user interaction. – Taslim Oseni Jul 05 '19 at 21:22
5

Simple Coding:

if(EditText1.isFocused()){
  //EditText1 is focused
}else if(EditText2.isFocused()){
  //EditText2 is focused
}
Umasankar
  • 495
  • 7
  • 6
  • This won't compile unless you named your variables with capital `E`, in which case Lint should crash your build anyway for both Kotlin and Java. And also, there has already been an answer with this solution. – milosmns Nov 01 '19 at 18:19
5

This worked for me using Java 8 (lambdas):

EditText myEditText = findViewById(R.id.editText);

myEditText.setOnFocusChangeListener((view, hasFocus) -> {
      if(hasFocus){
          Log.e("TAG", "myEditext has focus") 
      }else{
          Log.e("TAG", "myEditext has no focus") 
      }
});
ali sampson
  • 321
  • 4
  • 7
2

In your activity or fragment implement OnFocusChangeListener.

edittextNeme= (EditText) findViewById(R.id.edittextNeme);
edittextNeme.setOnFocusChangeListener(this);

You will have to check which view changed focus by getting the view id with view.getId() and handle accordingly.

@Override
public void onFocusChange(View view, boolean hasfocus) {
    switch(view.getId()){
    case R.id.edittextNeme:
    //Do something
    break;

    ...etc
    }
}
Sayan Manna
  • 584
  • 7
  • 13
1
val currentFocusView = activity.currentFocus
if (currentFocusView is EditText){
   currentFocusView.appendText("Has Focus!")
}
NickUnuchek
  • 11,794
  • 12
  • 98
  • 138
  • Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jun 20 '22 at 02:43