Reputation: 778
When you press on a button in Android it changes color. I want it to stay like that. I mean i want something like this:
Button btn = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn.setBackGroundColor(R.drawable.clicked /*clicked style*/ );
}
});
example:
This is a pressed on button. I want it to stay like that after i stop pressing it. Is there a easy way like that:
android.R.drawable.btn_default //this is the default button style, i want the pressed one :D
Upvotes: 0
Views: 1780
Reputation: 4258
So you want it to start non-pressed and then stay pressed after being clicked one?
Try using an OnTouchListener instead adding btn.setPressed(true);
:
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
btn.setPressed(true);
}
return true;
}
Upvotes: 1
Reputation: 7092
You can try this way either put image as dark when press or color
drawable/selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_focused="true" android:drawable="@drawable/buttondark"/>
<item android:state_pressed="true" android:drawable="@drawable/buttondark" />
<item android:drawable="@drawable/button" />
</selector>
inside on-create method write
btn.setBackgroundResource(R.drawable.selector);
Upvotes: 0
Reputation: 3745
Try using selector:
Define selector.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed_yellow"
android:state_pressed="true" />
<item android:drawable="@drawable/button_normal_green" />
</selector>
and set background of the button to android:background="@drawable/selector"
then in the code on the click event of the button set btn.setpressed(true);
Upvotes: 1
Reputation: 7207
Take a look of the StateSelector images
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
You can set diferent resources for the diferent states of your button/view. This example set different colors:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/branded_content_pressed_color" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@color/branded_content_pressed_color" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@color/branded_content_background_color"/>
</selector>
Then you can set the selector normally
button.setBackgroundResource(R.drawable.selector);
Upvotes: 0
Reputation: 1420
In your java code write button.setPressed(true);
.It will set button in pressed mode. You can change the parameter to true and false when you want to set it pressed and unpressed...
Upvotes: 1