如何更改android中按下按钮的边框颜色

时间:2017-10-09 12:28:53

标签: android

我尝试以编程方式处于按下状态时更改按钮的边框颜色。我这样做的原因是因为我制作了动态主题。下面你可以看到我的所有研究,但它并没有真正帮助我。

我找到了如何使用此示例中的XML进行更改Change border color when edittext is focused

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_enabled="true"
        android:state_pressed="true">
    <shape android:padding="10dp" android:shape="rectangle">
        <solid android:color="#FFFFFF" />
        <stroke android:width="2dp" android:color="#ffa0a496" />
        <corners android:bottomLeftRadius="15dp" android:bottomRightRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp" />
    </shape>
</item>
<item android:state_enabled="true">
    <shape android:padding="10dp"
        android:shape="rectangle">
        <solid android:color="#FFFFFF" />
        <corners android:bottomLeftRadius="15dp" android:bottomRightRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp" />
    </shape>
</item>

下面的代码会根据我从这里获得的按钮Android create selector programmatically

更改背景颜色
public static StateListDrawable makeSelector(int color) {
    StateListDrawable res = new StateListDrawable();
    res.setExitFadeDuration(400);
    res.setAlpha(45);
    res.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(color));
    res.addState(new int[]{}, new ColorDrawable(Color.TRANSPARENT));
    return res;
}
view.setBackground(makeSelector(Color.RED));

此代码以编程方式更改边框颜色,但未指定我从此处获取的状态Android Button or TextView Border programmatically without using setBackgroundDrawable method

    GradientDrawable gd = new GradientDrawable();
    gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
    gd.setCornerRadius(5);
    gd.setStroke(1, 0xFF000000);
    TextView tv = (TextView)findViewById(R.id.textView1);
    tv.setBackgroundDrawable(gd);

0 个答案:

没有答案