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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27492401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:52:56  来源:igfitidea点击:

How to change the stroke width of a shape programmatically in Android?

javaandroidshape

提问by Taha K?rkem

This is circle.xml

这是 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>

This is my code:

这是我的代码:

textview.setBackgroundResource(R.drawable.circle);

I want to change the stroke thickness in my java code. How can I change it programmatically?

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

采纳答案by browep

You may need to create it programmatically

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

ShapeDrawable circle = new ShapeDrawable( new  OvalShape() );

you need to set the properties after this, ( padding, color, etc) then change its stroke

您需要在此之后设置属性(填充、颜色等),然后更改其笔划

circle.getPaint().setStrokeWidth(12);

then set it as the background for the view

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

textview.setBackgroundDrawable(circle);

回答by eldivino87

Do like this:

这样做:

1) Get the TextViewusing the usual findViewById():

1)获取TextView使用通常的findViewById()

TextView textView = (TextView) rootView.findViewById(R.id.resourceName);

2) Get the Drawablefrom TextViewusing getBackground()and cast it to GradientDrawable:

2)DrawableTextViewusing 中获取getBackground()并将其转换为GradientDrawable

GradientDrawable backgroundGradient = (GradientDrawable) textView.getBackground();

3) Apply it a stroke using setStroke()method (pass it the width in pixel and the color):

3)使用setStroke()方法将其应用为笔触(以像素和颜色为单位传递宽度):

backgroundGradient.setStroke(5, Color.BLACK);

Whole code:

全码:

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