I made android and arduino applications that control my standing desk. I upload this project on 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>
I wanted to use selector for buttons in MainActivity. If I press some button then an image of the button must be changed. But It didn't work. So I programatically change an image of the button by checking 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;
}
});
Also I wrote following codes for selector in the layout xml file.
<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" />
Change this
android:src="@drawable/selector_down_button"
to
android:background="@drawable/selector_down_button"
You would probably want to enable the Pressed state when you get ACTION_DOWN event and disable it when you get the ACTION_UP event.
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");
view.setPressed(true);
break;
case MotionEvent.ACTION_UP:
btnDown.setImageResource(R.drawable.down_button);
sendCommand("s");
view.setPressed(false);
break;
}
return true;
}
});
Just try this
android:background="@drawable/selector_down_button"
Set selector as a background
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With