Android:禁用/启用ImageButton并显示不同的颜色

时间:2017-05-01 18:57:59

标签: android

我是Android开发的新手。我想实现以下功能,但对如何做到这一点感到困惑:

  1. 最初,图像按钮为DISABLED,颜色(色调)为灰色。
  2. 单击图像按钮时,意味着启用按钮,按钮的颜色(色调)变为橙色(或其他颜色),不返回灰色。
  3. 再次单击图像按钮时,意味着禁用按钮,颜色再次变为灰色。
  4. 我尝试过的代码如下所示:

    clickbutton_mic.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" >
            <bitmap
                android:src="@drawable/big_mic_icon"
                android:tint="@android:color/darker_gray"
                />
        </item>
        <item android:state_enabled="true" >
            <bitmap
                android:src="@drawable/big_mic_icon"
                android:tint="@android:color/holo_orange_dark"
                />
        </item>
        <item android:drawable="@drawable/big_mic_icon"/>
    
    </selector>
    

    main_page.xml

    的一部分
     <ImageButton
            android:id="@+id/imageButton"
            android:layout_width="72dp"
            android:layout_height="73dp"
            android:background="@android:color/transparent"
            android:onClick="onClick"
            android:src="@drawable/clickbutton_mic" />
    

    MainPage.java

    的一部分
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_page);
            ImageButton btn = (ImageButton) findViewById(R.id.imageButton);
            btn.setEnabled(false);
        }
    
    public void onClick(ImageButton btn)
        {
            if(!btn.isEnabled()){
                btn.setEnabled(true);
            }
            else{
                btn.setEnabled(false);
            }
        }
    

    此代码的结果始终显示黑色图标(原始图标颜色,灰色或橙色)。 我在stackoverflow上找到了一些关于禁用/启用图像按钮的问题,但答案对我来说并不清楚。那么有人可以帮我处理这种情况吗?谢谢!

1 个答案:

答案 0 :(得分:0)

由我自己解决。我误解了&#34; setEnabled&#34;的含义。我的以下代码实现了我想要的。

private int MIC_STATUS = 0; // MIC OFF
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        final ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(MIC_STATUS == 0){ // mic is off, turn on the mic
                    imageButton.setColorFilter(Color.rgb(255,42,72));
                    MIC_STATUS = 1;
                }

                else if(MIC_STATUS == 1){ // mic is on, turn off the mic
                    imageButton.setColorFilter(Color.WHITE);
                    MIC_STATUS = 0;
                }

            }
        });
}