Button is not calling OnClickListener with first click Button is not calling OnClickListener with first click xml xml

Button is not calling OnClickListener with first click


You are setting android:focusableInTouchMode="true"Hence on 1st click it receives focus.

Refer Android button - How to set focusable to true and still accept onClick listener on first click?


Set this -

android:focusableInTouchMode="true"

to this -

android:focusableInTouchMode="false"

on button.

Explanation - If you'll make the button focusable then on first click the focus is passed to the button, then the click is passed on second touch. EditText is a focusable View which gains focus first and therefore other views must first regain the focus from EditText, unless they do not need focus to work, just like buttons. If you just need the OnClick function, then you don't need focus, so you can spre one extra click.

PS: Although it shouldn't require, but setting android:focusable to false will help too, if the first one doesn't work.


Yes Yes I got the answer, after a lot of RND, I got the solution, I just need to implement setOnClickListener(), and setOnFocusChangeListener(). So I am putting here the solution.

ActivityLogin.java

 buttonLogin= (Button) findViewById(R.id.buttonLogin);    buttonLogin.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {            Log.d("hello", "hellow");            String username = mUserEditText.getText().toString();            String password = mPassEditText.getText().toString();            String location = mLocationData.get(mLocationSpinner.getSelectedItemPosition()).toLowerCase();            if(username.isEmpty()||password.isEmpty()){            popbox();                return;            }            User user;            user = new User(username);            user.setLocation(location);            AppManager.getInstance().setLoggedInUser(user);            APICaller.getInstance().login(username, password, location);        }    });    buttonLogin.setOnFocusChangeListener(new View.OnFocusChangeListener() {    public void onFocusChange(View v, boolean hasFocus) {        if (hasFocus) {            v.performClick();        }    }});}

activity_login.xml

  <Button        android:id="@+id/buttonLogin"        style="@style/Button1"        android:text="continue"         />