0

I am working on a login page of an activity where I have username and password as 2 EditText boxes. I am trying to display Toast message when focus is changed from username to password box : -If the text entered in username box has whitespace in it. -If no white space then no Toast display.

Mr Singh
  • 415
  • 1
  • 6
  • 14

3 Answers3

0
EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          

        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               if (txtEdit.getText().Contains(" ")) {
                 Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            }
        }
    });

Reference: https://stackoverflow.com/a/10627231/2111834

Community
  • 1
  • 1
Edwin Lambregts
  • 408
  • 6
  • 22
0

You can use View.OnFocusChangeListener for this.

Code sample:

et_uname.setOnFocusChangeListener(new View.OnFocusChangeListener(){
  @Override
  public void onFocusChange(View v, boolean hasFocus) {
     if (hasFocus == false && et_uname.getText().toString() != null && et_uname.getText().toString().contains(" ")){
        Toast.makeText(getActivity(), "Alert", Toast.LENGTH_LONG).show();                   
    }
  }
};

This is done for fragment. If inside Activity then you can replace

getActivity() 

with

<activityname>.this

Here hasFocus = true means et_uname currently has focus and hasFocus = false means do not have focus. As you require to alert user when focus is lost, have to add a condition for hasFOcus == false.

Rajen Raiyarela
  • 5,526
  • 4
  • 21
  • 41
0

You should implement OnFocusChangeListener for both your edit, see the code below:

 EditText myEdit = (EditText) findViewById(R.id.edit1);

 myEdit .setOnFocusChangeListener(new OnFocusChangeListener() {          

    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
           // Do the check for white spaces and display the Toast
        }
    }
});
Sid
  • 14,176
  • 7
  • 40
  • 48