简体   繁体   English

按钮在第二次点击Android上工作

[英]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. 哪个应该变成R.drawable.role_button_pressed然后我按它,或者如果我的按钮已经被按下它应该变成原始的R.drawable.role_button然后我按它。 But then i am pressing my button it need to be pressed twice to change it state. 但是,然后我按我的按钮,需要按两次以更改其状态。

My xml looks like this: 我的xml看起来像这样:

       <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;
            }
        }
    });

You have the wrong default boolean in the first place. 首先,您使用了错误的默认布尔值。 I assume the starting resource is R.drawable.role_button . 我假设起始资源是R.drawable.role_button

Change isPressed to false and put it into your clickListener, because it's not pressed right? isPressed更改为false并将其放入您的clickListener中,因为没有正确按下它?

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;
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM