问题
I use a xml file to color my button. In the xml a have this code to define the color of my button when it's clicked.
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="@color/mainRaddoppiaButtonBackgroundEnd"
android:endColor="@color/mainRaddoppiaButtonBackgroundStart"
android:angle="270" />
<stroke
android:width="0dp"
android:color="@color/mainRaddoppiaButtonBackgroundStart" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item android:state_focused="true" >
<shape>
<gradient
android:startColor="@color/mainRaddoppiaButtonBackgroundEnd"
android:endColor="@color/mainRaddoppiaButtonBackgroundStart"
android:angle="270" />
<stroke
android:width="0dp"
android:color="@color/mainRaddoppiaButtonBackgroundStart" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="@color/mainRaddoppiaButtonBackgroundStart"
android:endColor="@color/mainRaddoppiaButtonBackgroundEnd"
android:angle="270" />
<stroke
android:width="0dp"
android:color="@color/mainRaddoppiaButtonBackgroundStart" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
Is it possibile from java to keep my button pressed and color it with "state_pressed" values set in my xml file?
Someting like:
public void onClick(View button) {
button.seLayout(R.xml.xmlFileName.state_pressed)
}
Of course this code has no sense, i just made it up to let you understand what i want to do
回答1:
Try this.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_pressed"
android:state_pressed="true"/>
<item android:drawable="@drawable/btn_normal" />
</selector>
回答2:
use StateListDrawable for setting selector by code as:
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },getResources().getDrawable(R.drawable.normal));
button.setBackgroundDrawable(states);//FOR BUTTON
回答3:
Use this:
StateListDrawable states = new StateListDrawable(){
@Override
protected boolean onStateChange(int[] stateSet) {
//
}
};
itemView.setBackground(states);
来源:https://stackoverflow.com/questions/14397282/how-to-set-the-state-pressed-of-a-button