单击时TextView的角变为白色

时间:2014-05-07 07:06:42

标签: android textview statelistdrawable

我使用以下代码段来显示TextView

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.test);

GradientDrawable gd = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{0xffff0000,0xffff0000});
gd.setCornerRadius(10);
GradientDrawable gd1 = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{0xff00ff00,0xff00ff00});
gd1.setCornerRadius(10);
StateListDrawable background = new StateListDrawable();
background.addState(new int[]{android.R.attr.state_pressed}, gd1);
background.addState(StateSet.WILD_CARD, gd);
tv.setBackgroundDrawable(background);
tv.setClickable(true);

在正常状态下,它的外观是可以的: enter image description here

但单击时,四个角将变为白色,请参阅: enter image description here

我该如何避免这种情况?

1 个答案:

答案 0 :(得分:1)

在drawable文件夹下创建一个text_bg_selector.xml文件。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:state_pressed="true"
            android:drawable="@drawable/pressed_bg" /> <!-- pressed -->
        <item android:state_focused="true"
            android:drawable="@drawable/focused_bh" /> <!-- focused -->
        <item android:drawable="@drawable/default_bg" /> <!-- default -->
</selector>

然后将TextView的背景设置为:

android:background="@drawable/text_bg_selector"

编辑代码:

由于不推荐使用setBackgroundDrawable,您必须检查它并编写setBackground,如下所示:

GradientDrawable gd = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{0xffff0000,0xffff0000});
gd.setCornerRadius(10);
GradientDrawable gd1 = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{0xff00ff00,0xff00ff00});
gd1.setCornerRadius(10);
StateListDrawable background = new StateListDrawable();
background.addState(new int[]{android.R.attr.state_pressed}, gd1);
background.addState(new int[]{android.R.attr.state_focused}, gd1);
background.addState(StateSet.WILD_CARD, gd);
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    t.setBackgroundDrawable(background);
} else {
    t.setBackground(background);
}
t.setClickable(true);