目前,ImageButton
设置了android:background =“@ drawable / mem_btn”,
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="0dp" android:color="@color/black" />
<solid android:color="@color/pressed"/>
<padding android:left="5dp" android:top="5dp"
android:right="5dp" android:bottom="5dp" />
<corners android:radius="14dp" />
</shape>
</item>
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="0dp" android:color="@color/black" />
<solid android:color="#3366CC"/>
<padding android:left="5dp" android:top="5dp"
android:right="5dp" android:bottom="2dp" />
<corners android:radius="14dp" />
</shape>
</item>
</selector>
以上工作完美。
我想让用户更改背景颜色:即用户选择的其他颜色,但使用pressed_color,半径保持不变。
在这种情况下,如何以编程方式设置xml中的信息,使得非按下状态的颜色是变量?
谢谢!
答案 0 :(得分:2)
感谢Ranjit Pati的参考,以便我可以在正确的轨道上进一步研究并找到StateListDrawable
,以下工作完美:
public void set_buttons(int t, int color_idd)
{
ShapeDrawable activeDrawable = new ShapeDrawable();
ShapeDrawable inactiveDrawable = new ShapeDrawable();
// The corners are ordered top-left, top-right, bottom-right, bottom-left. // For each corner, the array contains 2 values, [X_radius, Y_radius]
float[] radii = new float[8];
for (int i = 0; i <= 7; i++)
{
radii[i] = (int) getResources().getDimension(R.dimen.footer_corners);
}
inactiveDrawable.setShape(new RoundRectShape(radii, null, null));
inactiveDrawable.getPaint().setColor(color_idd);
activeDrawable.setShape(new RoundRectShape(radii, null, null));
activeDrawable.getPaint().setColor( (Color.parseColor ("#008B00")));
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {-android.R.attr.state_enabled}, inactiveDrawable);
states.addState(new int[] {android.R.attr.state_pressed}, activeDrawable);
btns[t].setBackground(states);
}
答案 1 :(得分:0)
如果我的主要问题点正确,这个自定义按钮可以解决您的问题。
public class customButton extends Button{
int dColor, pColor;
public customButton(Context context, int defaultColor, final int pressedColor) {
super(context);
dColor = defaultColor;
pColor = pressedColor;
this.setBackgroundDrawable(getShape(defaultColor));
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundDrawable(getShape(pressedColor));
}
});
}
//A method that return a single color shape with radius corner
private Drawable getShape(int color){
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[] { color,
color, color});
gradientDrawable.setGradientType(GradientDrawable.RECTANGLE);
float[] f = {1,1,1,1,1,1,1,1}; //set the radius as you like
gradientDrawable.setCornerRadii(f);
return gradientDrawable;
}
//A method that change the default and pressed color of the button
public void changeColor(int defaultColor, int pressedColor){
this.setBackgroundDrawable(getShape(defaultColor));
pColor = pressedColor;
}
}