我在button中创建了一个layout。在Drawable文件夹中,我创建了一个名为XML filebtn01_statebtn01_state.xml分配给我通过“button”创建的android:background=@drawable/btn01_state
现在,button具有默认的image img1。当我在click上添加button时,image1更改为img2,并且一旦我释放了单击的鼠标按钮,image2再次更改为img1。

我想要做的是,通过点击evey来更改按钮的图像。

例如,最初
btn01具有img01

如果btn01被按下==>将btn01的img设置为img02并保持img02直到再次按下btn01。现在,btn01上面有img02。

按下btn01时,将img01设置为btn01。

我希望这使我想做的更多。

btn_selector :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/android_blue"
      android:state_pressed="true" />
<item android:drawable="@drawable/ic_launcher"
      android:state_focused="true" />
<item android:drawable="@drawable/ic_launcher" />

main.xml
<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:id="@+id/btn01"
    android:background="@drawable/btn01_state"/>

最佳答案

您可以在代码中轻松完成此操作。

boolean isPressed = false;
button.setOnClickListener(buttonListener);

OnClickListener buttonListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        if(isPressed)
           button.setBackgroundResource(R.drawable.icon1);
        else
           button.setBackgroundResource(R.drawable.icon2);

        isPressed = !isPressed;
   }
};

关于android - 每次单击如何更改按钮的图像?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10470288/

10-10 21:10