如何在Android中以编程方式更改形状的笔触宽度?

Tah*_*kem 8 java android shape

这是circle.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <solid android:color="#00000000"/> 
    <padding android:left="30dp" android:top="30dp"
             android:right="30dp" android:bottom="30dp" />
    <stroke android:color="#439CC8" android:width="7dp" />
</shape>
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

textview.setBackgroundResource(R.drawable.circle);
Run Code Online (Sandbox Code Playgroud)

我想在我的java代码中更改笔触粗细.如何以编程方式更改它?

eld*_*o87 11

这样做:

1)TextView通常使用findViewById():

TextView textView = (TextView) rootView.findViewById(R.id.resourceName);
Run Code Online (Sandbox Code Playgroud)

2)DrawableTextView使用中获取getBackground()并将其投射到GradientDrawable:

GradientDrawable backgroundGradient = (GradientDrawable) textView.getBackground();
Run Code Online (Sandbox Code Playgroud)

3)使用setStroke()方法应用它(以像素和颜色传递宽度):

backgroundGradient.setStroke(5, Color.BLACK);
Run Code Online (Sandbox Code Playgroud)

整码:

TextView textView = (TextView) rootView.findViewById(R.id.resourceName);
GradientDrawable backgroundGradient = (GradientDrawable) textView.getBackground();
backgroundGradient.setStroke(5, Color.BLACK);
Run Code Online (Sandbox Code Playgroud)


bro*_*wep 7

您可能需要以编程方式创建它

ShapeDrawable circle = new ShapeDrawable( new  OvalShape() );
Run Code Online (Sandbox Code Playgroud)

你需要在此之后设置属性,(填充,颜色等)然后改变它的笔划

circle.getPaint().setStrokeWidth(12);
Run Code Online (Sandbox Code Playgroud)

然后将其设置为视图的背景

textview.setBackgroundDrawable(circle);
Run Code Online (Sandbox Code Playgroud)