如何更改按钮的背景图片时,点击/集中?片时、按钮、如何更改、背景图

2023-09-12 07:18:58 作者:八度余温

我想改变一个按钮的背景图像单击或集中时。

I want to change the background image of a button when clicked or focused.

这是我的code:

Button tiny = (Button)findViewById(R.id.tiny);
tiny.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Button tiny = (Button)findViewById(R.id.tiny);
        tiny.setBackgroundResource(R.drawable.a9p_09_11_00754);

        TextView txt = (TextView)findViewById(R.id.txt);
        txt.setText("!---- On click ----!");
    }
});

这是code吗?它是否调用按钮的事件?

Is this code right? Does it calls a button on its event?

推荐答案

您可以在此XML文件执行如下:

you can implement in a xml file for this as follows:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/your_imagename_while_focused"/>
<item android:state_pressed="true" android:drawable="@drawable/your_imagename_while_pressed" />
<item android:drawable="@drawable/image_name_while_notpressed" />  //means normal
</selector>

现在保存在文件夹中绘制此xml文件并将其命名suppos abc.xml并设置如下:

now save this xml file in drawable folder and name it suppos abc.xml and set it as follows

 Button tiny = (Button)findViewById(R.id.tiny);
 tiny.setBackgroundResource(R.drawable.abc);

希望它会帮助你。 :)

Hope it will help you. :)