我有一个按钮,我想打开按钮,比如打开和关闭,我需要的是我有两个背景图像。
当我第一次点击按钮时,第一个背景图像应该完成,第二次第二个背景图像应该像切换按钮一样改变。
任何人都请帮助我,因为我是 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/