android - 如何更改点击按钮的背景?

标签 android

我有一个按钮,我想打开按钮,比如打开和关闭,我需要的是我有两个背景图像。

当我第一次点击按钮时,第一个背景图像应该完成,第二次第二个背景图像应该像切换按钮一样改变。

任何人都请帮助我,因为我是 android 的新手。

这是我的 Activity :

public class MainActivity extends Activity {

    private Button Button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button1 = (Button) findViewById(R.id.Button1);
        Button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                v.setBackgroundResource(R.drawable.ic_launcher);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}  

谢谢。

最佳答案

使用以下代码在drawable中创建一个xml文件,并将按钮的背景更改为这个drawable

自定义按钮.xml

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

然后给图片添加背景

<ImageView
    android:layoutWidth="wrap_content"
    android:layoutWidth="wrap_content"
    android:background="@drawable/customButtom" />

关于android - 如何更改点击按钮的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19954999/

相关文章:

java - 无法从 FragmentActivity 更改 Fragment 内的 TextView 值

android - 如何在 Jetpack Compose 中为 TextField 设置 inputType

android - 导航栏 - 滚动时不会在 body 前面

android - Eclipse 和自动截图

android - 连接到Firebase Cloud Messaging时出错

java - 对设置彩色图像的中值感到困惑

android - 无法解析符号 AppCompatActivity - 无法识别支持 ​​v7 库?

android - 在 Android Studio 中为单元测试设置自定义 Assets 目录

java - 从矩形数组中检索矩形时出现空指针异常

java - 在 Android 中使用显式 Intent 进行文本比较