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

怎甘沉沦 提交于 2020-01-13 08:45:10

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/27492401/how-to-change-the-stroke-width-of-a-shape-programmatically-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!