D1's D1's - 22 days ago 8
Java Question

Button working on second click android

I have a button in my Fragment. Which supposed to turn into R.drawable.role_button_pressed then i press it or if my button is already pressed it supposed to turn into original R.drawable.role_button then i press it. But then i am pressing my button it need to be pressed twice to change it state.

My xml looks like this:

<Button
android:id="@+id/role"
android:layout_width="40dp"
android:layout_height="40dp"
android:gravity="center"
android:layout_marginTop="@dimen/margin_role_buttons_top"
android:layout_marginRight="@dimen/margin_role_buttons_right"
android:layout_marginBottom="@dimen/margin_role_button_bot"
android:text="@string/jungle"
android:textColor="@android:color/black"
android:layout_below="@id/divider4"
android:layout_toLeftOf="@id/role_mid_lookingfor"
android:background="@drawable/role_button" />


and on click method

boolean isPressed = true;

Button rolebutton = (Button) v.findViewById(R.id.role);

rolebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isPressed){
rolebutton.setBackgroundResource(R.drawable.role_button_pressed);
isPressed=true;
}else if(isPressed==true){
rolebutton.setBackgroundResource(R.drawable.role_button);
isPressed=false;
}
}
});

Answer

You have the wrong default boolean in the first place. I assume the starting resource is R.drawable.role_button.

Change isPressed to false and put it into your clickListener, because it's not pressed right?

And I suggest you to use a better shortcut in your if else

rolebutton.setOnClickListener(new View.OnClickListener() {
    boolean isPressed = false;

    public void onClick(View v) {

   rolebutton.setBackgroundResource(isPressed ? R.drawable.role_button : R.drawable.role_button_pressed));
   isPressed = !isPressed;
}
}
Comments