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

11

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

这是我的代码:

textview.setBackgroundResource(R.drawable.circle);

我想在我的Java代码中更改描边的粗细。我该如何以编程方式更改它?

2个回答

16

按照以下步骤进行:

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

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

2) 使用 getBackground() 方法从 TextView 获取 Drawable,并将其转换为 GradientDrawable

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

3) 使用setStroke()方法对其应用描边(传递像素宽度和颜色):

backgroundGradient.setStroke(5, Color.BLACK);

整个代码:

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

8

你可能需要通过编程来创建它

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

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

circle.getPaint().setStrokeWidth(12);

然后将其设置为视图的背景。
textview.setBackgroundDrawable(circle);

myView --- 这是什么变量? - Taha Körkem
1
无论您正在尝试设置背景的视图是什么,对于您的情况,它是TextView。我会更新我的答案。 - browep
我的应用程序在这一行停止了:ShapeDrawable myCircle = (ShapeDrawable) getResources().getDrawable(R.drawable.circle); - Taha Körkem
12-15 16:52:13.320: E/AndroidRuntime(1454): java.lang.ClassCastException: android.graphics.drawable.GradientDrawable无法转换为android.graphics.drawable.ShapeDrawable - Taha Körkem
我已经更新了我的答案,你可能需要以编程方式完成这个。 - browep
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接