我正在尝试以编程方式更改 TextView
的边框颜色,具体取决于 Activity 中的 if
条件。这是我的 ViewContact.java
代码:
if (bob == 0) {
//change colour depending on value
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat
.getDrawable(ViewContact.this,R.drawable.textboxes);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.textbox_shape);
gradientDrawable.setColor(Color.parseColor("#DA850B")); // change color
}
if (bob == 1) {
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat
.getDrawable(ViewContact.this,R.drawable.textboxes);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.textbox_shape);
gradientDrawable.setColor(Color.parseColor("#0A7FDA")); // change color
}
if (bob == 2) {
etc...
}
我看过这里Changing color in a shape inside a layer-list programmatically在这里 Android change color stroke (border) programmatically和其他地方寻求解决方案,但无法使其正常工作。
这是 ViewContact.java
Activity 中 TextView
的 xml
,activity_view_contact.xml
:
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:background="@drawable/textboxes"
/>
这是textboxes.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--space between each text box-->
<item
android:top="3dp"
android:id="@+id/textbox_shape"
>
<shape android:shape="rectangle">
<!--formatting of colour inside the box-->
<solid android:color="@android:color/transparent" />
<!--formatting of lines on the box-->
<stroke
android:width="1dip"
/>
<corners android:radius="3dp"/>
<!--text formatting in the box-->
<padding
android:textSize="30dp"
android:top="15dp"
android:bottom="1dp"
android:left="20dp"
android:right="20dp"/>
</shape>
</item>
</layer-list>
最佳答案
您正在更改加载的可绘制对象的颜色,而不是 TextView
中使用的颜色。将以下行添加到代码中以在 TextView
中设置背景可绘制元素:
findViewById(R.id.textView1).setBackground(layerDrawable);
您还可以直接使用
获取TextView
的背景
LayerDrawable layerDrawable = (LayerDrawable) findViewById(R.id.textView1).getBackground();
这是一组更改背景和描边颜色的代码:
LayerDrawable layerDrawable = (LayerDrawable) findViewById(R.id.textView1).getBackground();
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.textbox_shape);
// Change background color
gradientDrawable.setColor(Color.parseColor("#DA850B"));
// Change stroke color. (Assumes 5px stroke width.)
gradientDrawable.setStroke(5, Color.parseColor("#FF0000"));
关于android - 如何以编程方式设置 TextView 的边框颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54021762/