Having this selector XML file:
<?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/z01_pressed" /> <!-- pressed -->
<item android:state_active="true"
android:drawable="@drawable/z01_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/z01_pressed" /> <!-- focused -->
<item android:drawable="@drawable/z01" /> <!-- default -->
</selector>
Can I modify it (or have a programmatic way) to do this in Android:
When you click and hold an ImageButton and move you finger to another ImageButton the other one gets the effect (The pressing effect) and the f开发者_如何学JAVAirst one returns to its normal state.
So, If you have multiple buttons in your screen and you slide your finger in top of them, each one gets the press effect when the finger is above it
Can this be done in XML? Code? In API 4 ? or above?
Is this even possible?
Thanks
To those who might be interested:
I couldn't find a solution to my problem under API level 4. So, I gave up !
You can do this by using an onTouchListener and a Region object for each button. First you need to find the size of each button to be able to determine the size of the Region objects:
EDIT:
final ImageButton button = (ImageButton) findViewById(R.id.imagebutton);
int width = 128; // The width of the button
int height = 64; // The height of the button
int[] pos = new int[2];
button.getLocationInWindow(pos);
final ImageButton button2 = (ImageButton) findViewById(R.id.imagebutton2);
int width2 = 128; // The width of the button
int height2 = 64; // The height of the button
int[] pos2 = new int[2];
button2.getLocationInWindow(pos2);
final Region region2 = new Region(pos2[0], pos2[1], pos2[0] + width, pos2[1] + height);
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
if(region1.contains((int)event.getX(), (int)event.getY())) {
button.setImageResource(R.drawable.z01_pressed);
button2.setImageResource(R.drawable.z01);
} else if(region2.contains((int)event.getX(), (int)event.getY())) {
button2.setImageResource(R.drawable.z01_pressed);
button.setImageResource(R.drawable.z01);
else {
button.setImageResource(R.drawable.z01);
button2.setImageResource(R.drawable.z01);
}
}
else {
button.setImageResource(R.drawable.z01);
button2.setImageResource(R.drawable.z01);
}
return false;
}
});
精彩评论