I'm working on an app in Android studios and would like my customised button to get bigger when pressed and go back to the default defined state when released. I wrote an xml file to define my button but it didn't work. Here's my xml file for the custom button:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/play_button_pressedhdpi"
android:state_pressed="true" />
<item android:drawable="@drawable/play_button_defaulthdpi"
android:state_focused="true" />
<item android:drawable="@drawable/play_button_defaulthdpi" />
</selector>
This doesn't seem to work. Any help would be appreciated.
Edit:
I just tried the following code as mentioned in the first answer below:
button1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) v.getLayoutParams();
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
//sendMessage("Key1\n");
lp.width = 200;
lp.height = 200;
button1.setLayoutParams(lp);
}
if(event.getAction() == MotionEvent.ACTION_UP) {
lp.width=90;
lp.height=90;
button1.setLayoutParams(lp);
}
return false;
}
});
This makes sense but didn't work for some reason.
Any help would be appreciated...
I was finally able to solve the problem. I created two separate images of two different sizes and used the setOnTouchListener() to assign the appropriate image to the button for each of the states ACTION_DOWN
and ACTION_UP
in the following manner:
button1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
float x = (float) 1.25;
float y = (float) 1.25;
button1.setScaleX(x);
button1.setScaleY(y);
button1.setBackgroundResource(R.drawable.blue_220);
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
float x = 1;
float y = 1;
button1.setScaleX(x);
button1.setScaleY(y);
button1.setBackgroundResource(R.drawable.blue_206);
}
return false;
}
});
Result as desired.