我制作了控制电动升降桌的安卓和Arduino应用程序。我将这个项目上传到Github(https://github.com/neosarchizo/MyStandingDesk)。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/down_button_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/down_button" />
</selector>
我想在MainActivity中使用选择器来为按钮设置样式。如果我按下某个按钮,那么该按钮的图像必须更改。但是它没有起作用。所以我通过检查MotionEvent来编程更改按钮的图像。
btnDown.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
btnDown.setImageResource(R.drawable.down_button_pressed);
sendCommand("a");
break;
case MotionEvent.ACTION_UP:
btnDown.setImageResource(R.drawable.down_button);
sendCommand("s");
break;
}
return true;
}
});
同时,我还在布局XML文件中为选择器编写了以下代码。
<ImageButton
android:id="@+id/btnDown"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_margin="30dip"
android:layout_weight="1"
android:scaleType="fitCenter"
android:background="@android:color/transparent"
android:src="@drawable/selector_down_button" />