0

我使用以下代码片段来显示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);

在正常状态下,它的外观是可以的: 在此处输入图像描述

但是当它被点击时,四个角会变成白色,看这个: 在此处输入图像描述

我怎样才能避免这种情况?

4

1 回答 1

1

在您的可绘制文件夹下创建一个 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);
于 2014-05-07T07:36:14.230 回答