简体   繁体   中英

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

This is 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?

Do like this:

1) Get the TextView using the usual findViewById() :

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

2) Get the Drawable from TextView using getBackground() and cast it to GradientDrawable :

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

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

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM