【问题标题】:How to change the stroke width of a shape programmatically in Android?如何在Android中以编程方式更改形状的笔触宽度?
【发布时间】:2014-12-15 20:17:29
【问题描述】:

这是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 代码中更改笔画粗细。如何以编程方式更改它?

【问题讨论】:

    标签: java android shape


    【解决方案1】:

    这样做:

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

    【讨论】:

      【解决方案2】:

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

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

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

      circle.getPaint().setStrokeWidth(12);
      

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

      textview.setBackgroundDrawable(circle);
      

      【讨论】:

      • myView --- 这个变量是什么?
      • 无论您尝试在什么视图上设置背景。你的情况下的文本视图。生病更新我的答案
      • 我的应用停止了这一行:ShapeDrawable myCircle = (ShapeDrawable) getResources().getDrawable( R.drawable.circle );
      • 12-15 16:52:13.320: E/AndroidRuntime(1454): java.lang.ClassCastException: android.graphics.drawable.GradientDrawable 不能转换为 android.graphics.drawable.ShapeDrawable跨度>
      • 我已经更新了我的答案,您可能需要以编程方式进行此操作
      猜你喜欢
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 2013-01-13
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多