我根据某些条件动态设置textview的背景
textview.setBackgroundResource(R.drawable.attempted_question_border);
OR
textview.setBackgroundResource(R.drawable.skipped_question_background);
背景的Xml是
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid
android:color="@color/answered_que_bg" >
</solid>
<stroke
android:width="1dp"
android:color="@color/answered_que_bg" >
</stroke>
<corners
android:radius="2dp">
</corners>
</shape>
设置背景颜色'answers_que_bg'和边框颜色'answers_que_bg'或背景颜色'skipped_question_background'和边框颜色'skipped_question_background'。到现在为止还挺好。现在我需要仅更改此textview 保持背景颜色相同的边框颜色。我尝试用xml以下更改背景。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="@color/bookmark_color" >
</stroke>
<corners
android:radius="2dp">
</corners>
</shape>
根据需要更改边框颜色,但背景颜色也会丢失。
答案 0 :(得分:1)
我已经通过将TextView放入LinearLayout来实现这一点,其中TextView将以两侧的某些边距为中心,然后我改变LinearLayout的背景颜色,而不更改textview的背景颜色,然后它看起来好像它的边框颜色已经改变了。
答案 1 :(得分:1)
将您的drawable xml与
这样的图层列表一起使用
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/shape">
<shape
android:shape="rectangle" >
<solid
android:color="@color/colorPrimary" >
</solid>
<stroke
android:width="1dp"
android:color="@color/colorPrimary" >
</stroke>
<corners
android:radius="2dp">
</corners>
</shape>
</item>
</layer-list>
代码以编程方式更改笔划也是背景
LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(demo.this,R.drawable.drawtext);
GradientDrawable gradientDrawable = (GradientDrawable) shape.findDrawableByLayerId(R.id.shape);
// if you want to change the color of background of textview dynamically
//gradientDrawable.setColor(ContextCompat.getColor(demo.this,R.color.colorAccent));
// This is mangage the storke width and it's color by this shape.setStroke(strokeWidth,color);
gradientDrawable.setStroke(2,ContextCompat.getColor(demo.this,R.color.colorAccent));
text2.setBackground(shape);
使用您的代码而不更改笔画颜色
使用我的代码更改笔画的颜色,您也可以在评论代码中以编程方式更改背景