I am using custom action bar in an Android app, which has custom ImageButtons on the right, with their onClick behaviour added programatically (see code snippet below).

XML source of the button

<ImageButton
        android:id="@+id/btn_refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/btn_right_menu"
        android:background="@null"
        android:contentDescription="@string/image_description"
        android:onClick="refresh"
        android:padding="10dp"
        android:src="@drawable/button_refresh" />

OnClickListener source

mRefreshButton = (ImageButton) findViewById(R.id.btn_refresh);
mRefreshButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
            doSomething();
    }
});

I would like to change the background color of my ImageButton programatically (without having to use additional graphics), so that the background would change when the user clicks on the button (after the click the background should go back to normal, i.e. transparent). How do I do that?

有帮助吗?

解决方案

Use a selector for your ImageButton and set background from xml.

If you want to use Drawable Images:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:state_pressed="true"
            android:drawable="@drawable/pressed_bg" /> <!-- pressed -->
        <item android:state_focused="true"
            android:drawable="@drawable/focused_bh" /> <!-- focused -->
        <item android:drawable="@drawable/default_bg" /> <!-- default -->
</selector>

If you want to use just color:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">     
     <item android:state_selected="true" android:drawable="@android:color/white" />    
     <item android:state_pressed="true" android:drawable="@android:color/white" />
     <item android:drawable="@android:color/transparent" />
</selector>

其他提示

The invalidate() method will force a redraw of any view:

Try using this:

mRefreshButton = (ImageButton) findViewById(R.id.btn_refresh);
mRefreshButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
           Drawable replacer = getResources().getDrawable(R.drawable.replacementGraphic);
    mRefreshButton .setBackgroundDrawable(replacer);
    mRefreshButton .invalidate();
    }
});

See here for reference.

To change color you can use the following

Btn.setBackgroundColor(Color.BLUE);

To set back to transparent

Btn.setBackgroundColor(Color.parseColor("#000000"));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top