我正在开发Android应用程序。我想有4个按钮水平放置在屏幕的底部。在这4个按钮中,有2个按钮上有图像。按钮的边框应该是黑色的,边框应该尽可能薄。当我单击按钮时,我希望按钮的背景颜色应该更改为蓝色,而边框的颜色不会改变,并且应该保持该颜色一段时间。如何在Android中实现此场景?
发布于 2010-10-07 21:34:25
一种方法是在drawable
中创建一个名为whatever.xml的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/bgalt" />
<item
android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/bgalt" />
<item android:drawable="@drawable/bgnorm" />
</selector>
bgalt
和bgnorm
是可绘制的PNG图像。
如果在activity中以编程方式创建按钮,则可以使用以下命令设置背景:
final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));
如果您使用XML设置按钮的样式,您将执行如下操作:
<Button
android:id="@+id/mybutton"
android:background="@drawable/watever" />
最后是一个link to a tutorial。希望这能有所帮助。
发布于 2013-04-08 21:42:19
使用"bg_button.xml“将此代码保存在可绘制文件夹中,并调用"@ drawable /bg_ button”作为按钮的背景:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid
android:color="#004F81" />
<stroke
android:width="1dp"
android:color="#222222" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#89cbee"
android:endColor="#004F81"
android:angle="270" />
<stroke
android:width="1dp"
android:color="#4aa5d4" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
发布于 2015-03-15 22:11:54
尝尝这个
final Button button = (Button) findViewById(R.id.button_id);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
button.setBackgroundColor(Color.RED);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
button.setBackgroundColor(Color.BLUE);
}
return false;
}
});
https://stackoverflow.com/questions/3882064
复制相似问题