我正在做一个 Andorid 测验,我想在点击按钮时突出显示按钮,但当用户松开按钮时,它会变成原来的颜色。你看,我已经设置了按钮的背景,这样按钮就可以变圆了。我已将其设置为可绘制。
<Button
android:id="@+id/btn1"
android:background="@drawable/roundedbutton"
android:textColor="#ffffff"
android:textStyle="italic"
android:layout_width="225sp"
android:layout_marginTop="23sp"
android:layout_height="38sp"
android:layout_alignLeft="@+id/btn2"
android:layout_below="@+id/textView1"
android:text="Button" />
圆形按钮.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#848482"/> <!-- this one is ths color of the Rounded Button -->
<corners
android:bottomRightRadius="6.5dp"
android:bottomLeftRadius="6.5dp"
android:topLeftRadius="6.5dp"
android:topRightRadius="6.5dp"/>
</shape>
最佳答案
您可以使用 OnTouchListener
或选择器。
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// change color
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
// set to normal color
}
return true;
}
});
您也可以使用选择器。边框和圆角矩形。自定义相同。
可绘制文件夹中的 bkg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/pressed" />
<item android:state_focused="false"
android:drawable="@drawable/normal" />
</selector>
drawable文件夹中的normal.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#0AECBF"/>
<stroke android:width="3dp"
android:color="#0FECFF" />
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
drawable 文件夹中的 pressed.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ff33ffff" />
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
现在在xml中为你的按钮设置背景
android:background="@drawable/bkg"
关于android - 按下时如何突出显示按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17969925/