2016-11-11 157 views
0

我在我的片段中有一个按钮。其中应该变成R.drawable.role_button_pressed然后我按下它,或者如果我的按钮已经按下它应该变成原来的R.drawable.role_button然后我按下它。但后来我按了我的按钮,它需要按两次才能改变它的状态。按钮上的第二次点击android

我的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" /> 

和点击方法

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

你'其他if'可以通过只更换'else' –

+0

,但它没有什么区别 – TheDude

+2

没错它。它更快! :) –

回答

2

你必须摆在首位的错误的默认布尔值。 我假设起始资源是R.drawable.role_button

isPressed更改为false并将其放入您的clickListener中,因为它没有正确按下?

,我建议你在使用一个更好的快捷方式,如果别人

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

它仍然需要按两次:(也许这是一个bug? – TheDude

+0

@ D1的按钮的默认资源是什么?你可以发布XML? –

+0

XML张贴在我的问题 - > android:background =“@ drawable/role_button“ – TheDude

相关问题