short noOfClicks = 0; //declare it as top level state variable
Button mButton = (Button) findViewById(R.id.your_button);
mButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
++noOfClicks //this counts the number of times button is clicked
if( noOfClicks % 2 == 0 ){ //user has clicked the button from disable state
//do your work here
mButton.setAlpha(1.0f); // this will bring back button to its original opacity
}else { //user has clicked the button from enabled state
//do your work here
mButton.setAlpha(0.5f);// this will grey out the button(actually, it changes the opacity of the button and gives a disabled look to the button)
}
}
});
# 1 楼答案
你想要什么:
你需要一个功能,一旦点击
Button
,它就会进入禁用状态,下一次点击时,它就会回到激活状态问题:
正如@Stephen C所指出的,一旦
Button
被禁用,它就不能再次被点击并恢复到活动状态解决方案
因此,我们不必禁用
Button
,只需让用户感觉Button
被禁用方法:
刚刚发生的事:
每当用户点击
Button
,noOfClicks
将增加一,检查if-else
将确定Button
当前处于启用还是禁用状态,这取决于我们应用的setAplha()
方法,该方法控制Button
的不透明度结论:
老实说,我们只是使用了一个丑陋的黑客,它给用户提供了一种错误的感觉,即
Button
在他第一次单击它时被禁用,在他第二次单击它时被启用# 2 楼答案
我想你误解了什么。当一个按钮被禁用时,这意味着对它的所有点击都将被忽略。这将包括单击以启用它
简而言之,你的要求是行不通的
现在,你可以实现一个按钮,当你点击它时,它可以在“开”和“关”状态之间切换。有一个现有的控件:https://developer.android.com/guide/topics/ui/controls/togglebutton
这可能是你真正需要的