android - How to control the stroke color of a shape through code?
習慣沉默
習慣沉默 2017-06-27 09:19:00
0
2
1025

1. This is an xml style file:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 角度 -->
    <corners android:radius="2dp"/>
    <!-- 填充色 -->
    <solid  android:color="#ffffff"/>
    <!-- 描边 设置线宽及颜色 -->
    <stroke android:color="@color/colorAccent"
        android:width="1dp"/>
</shape>

2. Use this style in searchView


      <android.support.v7.widget.SearchView
            android:id="@+id/searchView_singer"
            android:layout_width="match_parent"
            android:layout_height="46dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/searviewtest"
            />

3. As for the requirement, now the stroke color needs to be controlled in the code, that is, the style color is dynamically changed.
The color does not exist in color.xml, nor can it be changed using the theme

4. Ask for help...

習慣沉默
習慣沉默

reply all(2)
巴扎黑

Get a GradientDrawable object through searchView.getBackground() (if the View is set to a Shape background).

Then use drawable.setStroke(1, Color.RED) to dynamically set the stroke. The first parameter 1 represents the width, and the second is the color.

大家讲道理
Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template