如何通过单击Android Java中的相同按钮来启用禁用的按钮?

时间:2019-09-29 09:36:10

标签: java android

我想禁用按钮,然后通过在android java应用程序中单击同一按钮来再次启用它。

2 个答案:

答案 0 :(得分:1)

我认为您误会了一些东西。禁用按钮后,这意味着对它的所有单击都将被忽略。这将包括单击以启用它。

简而言之,您要的内容无法正常工作。

现在,您可以实现一个按钮,单击该按钮即可在“打开”和“关闭”状态之间切换。有一个针对此的现有控件:https://developer.android.com/guide/topics/ui/controls/togglebutton

那可能正是您真正需要的。

答案 1 :(得分:0)

您要的内容:

您需要一种功能,一旦单击Button,它将进入禁用状态,而下次单击时,它将回到活动状态。

问题:

正如@Stephen C所指出的那样,一旦禁用Button,就无法再次单击它并使其恢复到活动状态。

解决方案

因此,除了禁用Button之外,我们还可以使用户感到Button被禁用了。

方法

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

            }
         });

刚刚发生的事情:

每当用户单击Button时,noOfClicks就会增加1,if-else检查将确定Button当前处于启用还是禁用状态,取决于我们应用setAplha()方法来控制Button的不透明度。

结论:

老实说,我们只是使用了一个丑陋的hack,它给用户带来了一种误解,即Button第一次单击时被禁用,而第二次单击时被启用。

相关问题