1

いくつかの ImageButtons があり、そのうちの 1 つを強制的に CheckBox のように動作させようとしています。ユーザーがボタンを押すと、ボタンの背景を「押された」(タップアンドホールドしたときのようなオレンジ色) と「通常の」状態の間で切り替えたいと思います。その方法は?以下のコードは実際にはそうしていません。

    public void btnErase_click(View v) {
        ImageButton btnErase = (ImageButton) findViewById(R.id.btnErase);
        if (pressed == true)
            btnErase.setBackgroundColor(Color.YELLOW);
        else        
            btnErase.setBackgroundColor(android.R.drawable.btn_default);
    }
4

4 に答える 4

2

First, provide the selector. Save it as drawable/button_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_checked="true" android:drawable="@android:color/yellow" />
    <item drawable="@android:drawable/btn_default" />

</selector>

Apply it to your button as background. In code

public void btnErase_click(View v) {
    ImageButton btnErase = (ImageButton) findViewById(R.id.btnErase);
    if (pressed) {
        btnErase.getBackground().setState(new int[]{android.R.attr.state_selected});
    } else {
        btnErase.getBackground().setState(new int[]{-android.R.attr.state_selected});
    }
}

But I don't think it's a good idea. If your button has two states better use ToggleButton .

于 2013-02-06T18:50:38.643 に答える
1

You could try this may be, to set different states through xml, save this in drawable and then set it as background to your button:

<item android:state_pressed="true"><shape>
        <solid android:color="#3c3c3c" />

        <stroke android:width="0.5dp" android:color="#3399cc" />

        <corners android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp" android:topLeftRadius="4dp" android:topRightRadius="4dp" />

        <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
    </shape></item>
<item><shape>
        <gradient android:angle="270" android:endColor="#171717" android:startColor="#505050" />

        <stroke android:width="0.5dp" android:color="#3399cc" />

        <corners android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp" android:topLeftRadius="4dp" android:topRightRadius="4dp" />

        <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
    </shape></item>

于 2013-02-06T18:50:15.947 に答える
1

in句setBackgroundResourceの代わりに使用する必要があります。は色ではないため、リソースのIDです。setBackgroundCOlorelseandroid.R.drawable.btn_defaul

于 2013-02-06T18:48:27.223 に答える
1

渡されたものを使用するView v必要があります。ImageButton を再度見つける必要はありません。

また、ボタンの背景を画像に設定している場合は、setBackgroundResource代わりにsetBackgroundColor

public void btnErase_click(View v) {
        ImageButton btnErase = (ImageButton) v;
        if (pressed == true)
            btnErase.setBackgroundColor(Color.YELLOW);
        else        
            btnErase.setBackgroundResource(android.R.drawable.btn_default);
    }
于 2013-02-06T18:53:11.507 に答える