更改android textview边框颜色而不更改背景
我正在根据以下条件动态设置textview的背景:更改android textview边框颜色而不更改背景,android,android-layout,Android,Android Layout,我正在根据以下条件动态设置textview的背景: textview.setBackgroundResource(R.drawable.attempted_question_border); 或 用于后台的Xml是 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangl
textview.setBackgroundResource(R.drawable.attempted_question_border);
或
用于后台的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>
它设置背景颜色“已回答的问题背景”和边框颜色“已回答的问题背景”或背景颜色“跳过的问题背景”和边框颜色“跳过的问题背景”。到现在为止,一直都还不错。现在我只需要改变这个文本视图的边框颜色,保持背景颜色不变。我尝试用下面的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>
它会根据需要更改边框颜色,但也会丢失背景颜色。我将TextView放入一个LinearLayout中,其中TextView将以两侧的某些边距居中,然后我会更改LinearLayout的背景颜色,而不会更改TextView的背景颜色,然后它会看起来好像它的边框颜色已经改变了 将您的可绘制xml与层列表结合起来,如下所示 在不改变笔划颜色的情况下使用您的代码 使用我的代码可以更改笔划的颜色,也可以在注释代码中以编程方式更改背景
使用
Drawable#setColorFilter
@Ram Mehar Deswal您需要其他Drawable您可以使用一个Drawable查看我的答案如果您还更改了textview的背景,请查看注释代码也请尝试我的答案@Ram
<?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>
<?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);