Android EditText onfocuschange is not working

14,093

Solution 1

you must implement OnFocusChangeListener in your activity class.

public class MainActivity extends Activity implements OnFocusChangeListener
{
    ....
    @Overrride
    public void onFocusChange(View v, boolean hasFocus)
    {
        ....
    }
    ....
}

I think you would be getting an exception when you type cast this into OnFocusChangeListener at the line (OnFocusChangeListener) this

EDIT::: I had a look into ur code. I think your implementation should be like this:

    celsiusText.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 after)
        {
            ....
        }

        @Override
        public void afterTextChanged(Editable s)
        {
            ....
        }
    });
    farenheitText.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 after)
        {
            ....
        }

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

put this code inside oncreate and remove the lines celsiusText.setOnFocusChangeListener((OnFocusChangeListener) this) and ferenheitText.setOnFocusChangeListener((OnFocusChangeListener) this)

Solution 2

some times clearfocus() solves this problem. try to call editText1.clearfocus() in onCreate() method or other suitable places of code.

Share:
14,093

Related videos on Youtube

Mahesh
Author by

Mahesh

Updated on June 04, 2022

Comments

  • Mahesh
    Mahesh almost 2 years

    I'm new to Android programming. My following program does a simple Farenheit to Celsius conversion. If you enter values in a Farenheit EditText it will convert it into Celsius for every keystroke entered.

    I'm getting the following errors, the Changes I make in Celsius edit text are not reflected in Fahrenheit.

    07-29 01:59:21.189: E/AndroidRuntime(1390): java.lang.NumberFormatException: Invalid float: ""
    

    Following is my MainActivity.java:

     public class MainActivity extends Activity {
        private EditText celsiusText;
        private EditText farenheitText;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            celsiusText = (EditText) findViewById(R.id.editText1);
            farenheitText = (EditText) findViewById(R.id.editText2);
            celsiusText.requestFocus();
            celsiusText.setOnFocusChangeListener((OnFocusChangeListener) this);
            farenheitText.setOnFocusChangeListener((OnFocusChangeListener) this);
        }
    
        public void onFocusChange(View v, boolean hasFocus) {            
             TextWatcher watcher1 = new TextWatcher() {
                 public void afterTextChanged(Editable s) {
    
                 }
    
                 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                     // empty
                 }
    
                 public void onTextChanged(CharSequence S,int start,int before, int count) {
                     float inputValue;
                     if (!S.toString().equals("")) {
                         inputValue = Float.parseFloat(S.toString());
                         (findViewById(R.id.editText1)).setText(String
                                   .valueOf(convertFahrenheitToCelsius(inputValue)));
                      } else {
                          (findViewById(R.id.editText1)).setText("");
                          return;
                      }
                  }
              };
    
              TextWatcher watcher2 = new TextWatcher() {
                   public void afterTextChanged(Editable s) {
                       // empty
                   }
    
                   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                       // empty
                   }
    
                   public void onTextChanged(CharSequence S,int start,int before, int count) {
                        float inputValue;
                        if (!S.toString().equals("")) {
                            inputValue = Float.parseFloat(S.toString());
                            (findViewById(R.id.editText2)).setText(String
                                    .valueOf(convertCelsiusToFahrenheit(inputValue)));
    
                         } else {
                             (findViewById(R.id.editText2)).setText("");
                             return;
                         }
                    }
                };
    
                if((v == findViewById(R.id.editText2)) && hasFocus) {
                    farenheitText.addTextChangedListener(watcher1);
                } else if ((v == findViewById(R.id.editText1)) && hasFocus) {
                    (findViewById(R.id.editText1)).setText("");
                    celsiusText.addTextChangedListener(watcher2);
                }
          }
    
          //Converts to celsius
          private float convertFahrenheitToCelsius(float fahrenheit) {
              return ((fahrenheit - 32) * 5 / 9);
          }
    
          // Converts to fahrenheit
          private float convertCelsiusToFahrenheit(float celsius) {
               return ((celsius * 9) / 5) + 32;
          }
    
    }
    

    My activity_main.xml:

      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingLeft="16dp"
        android:paddingRight="16dp" >
    
        <EditText
            android:id="@+id/editText1"
            android:layout_width="128dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="62dp"
            android:ems="10"
            android:inputType="numberSigned" >
    
            <requestFocus />
        </EditText>
    
        <EditText
            android:id="@+id/editText2"
            android:layout_width="128dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/editText1"
            android:layout_alignBottom="@+id/editText1"
            android:layout_alignParentRight="true"
            android:ems="10"
            android:inputType="numberSigned" />
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText1"
            android:layout_below="@+id/editText1"
            android:layout_marginTop="18dp"
            android:text="@string/celsius"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView1"
            android:layout_alignBottom="@+id/textView1"
            android:layout_alignRight="@+id/editText2"
            android:text="@string/fahrenheit"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
    </RelativeLayout>
    
    • Zain Ali
      Zain Ali almost 12 years
      The problem is here java.lang.NumberFormatException: Invalid float: "".Perhaps you are trying to cast an empty string to float.
  • Mahesh
    Mahesh almost 12 years
    When I declare the onFocusChange inside activity it is throwing error in onTextChanged method (Duplicate definition of the same method...). As you have said it had thrown error in the line (OnFocusListener) first but when I cleaned the project the error disappeared..
  • Mahesh
    Mahesh almost 12 years
    Sure PC.. I will update you as soon as I get hold of my comp in probably 5 hours or so.. Thanks a lot...
  • Mahesh
    Mahesh almost 12 years
    But I've a doubt how can we use the same text watcher, when we are going to use different actions(updating Celsius or Farenheit ) based on which view the focus is on.. I'm just putting it down in words please correct me if I'm wrong.. We are having a text watcher it will listen to any change in text and then based on the set focus the values will be updated.. E.g Any change in Celsius textbox is captured and in ontextchanged method we will check for onfocus, if it is on Celsius we will update Farenheit and Vice Versa..
  • PC.
    PC. almost 12 years
    plz mark it as the correct answer if this was helpful to you.
  • Mahesh
    Mahesh almost 12 years
    PC, I'v checked your solution, but it is kind of throwing error, As you know the edit text works in both ways.. We have to make the text watcher work based on the focus of the text box(or any other focus type listeners).. Since my code is making changes in the Fahrenheit text box when I edit Celsius text box, it is throwing stack overflow error.. So we ahve to make the textwatcher listen only when the focus is set. I'm struggling in implementing the focus change and textwatcher methods together..
  • PC.
    PC. almost 12 years
    you can always use hasFocus method inside text change @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(celsiusText.hasFocus() { ...<your code here> ... } }