【问题标题】:How to change shape color dynamically?如何动态改变形状颜色?
【发布时间】:2011-11-02 03:20:21
【问题描述】:

我有

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
    <solid
       android:color="#FFFF00" />
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
</shape>

<TextView
    android:background="@drawable/test"
    android:layout_height="45dp"
    android:layout_width="100dp"
    android:text="Moderate"
/>

所以现在我希望这个形状根据我从 Web 服务调用返回的信息来改变颜色。所以它可能是黄色、绿色或红色或其他颜色,具体取决于我从网络服务调用中收到的颜色。

如何更改形状的颜色?根据这些信息?

【问题讨论】:

标签: android android-layout xamarin.android shape


【解决方案1】:

你可以像这样简单地修改它

GradientDrawable bgShape = (GradientDrawable)btn.getBackground();
bgShape.setColor(Color.BLACK);

【讨论】:

  • 什么是 btn.getBackground?
  • 我在尝试这个建议时收到java.lang.ClassCastException: android.graphics.drawable.GradientDrawable cannot be cast to android.graphics.drawable.ShapeDrawable
  • 不起作用。你会得到一个演员错误。需要修复或接受其他答案
  • 这很好用。自编辑答案以来,以前的 cmets 已过时!
  • 应该使用 GradientDrawable bgShape = (GradientDrawable)b​​tn.getBackground().getCurrent();
【解决方案2】:

对我来说,它崩溃了,因为 getBackground 返回了 GradientDrawable 而不是 ShapeDrawable

所以我这样修改:

((GradientDrawable)someView.getBackground()).setColor(someColor);

【讨论】:

    【解决方案3】:

    这对我有用,带有初始 xml 资源:

    example.setBackgroundResource(R.drawable.myshape);
    GradientDrawable gd = (GradientDrawable) example.getBackground().getCurrent();
    gd.setColor(Color.parseColor("#000000"));
    gd.setCornerRadii(new float[]{30, 30, 30, 30, 0, 0, 30, 30});
    gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);
    

    以上结果:http://i.stack.imgur.com/hKUR7.png

    【讨论】:

    • 这是正确答案。上面提到的两个答案都不适合我。我在这两个方面都遇到了例外。
    【解决方案4】:

    您可以在 Java 中构建自己的形状。 我为像 Page Controler 这样的 iPhone 做了这个,并用 Java 绘制形状:

    /**
     * Builds the active and inactive shapes / drawables for the page control
     */
    private void makeShapes() {
    
        activeDrawable = new ShapeDrawable();
        inactiveDrawable = new ShapeDrawable();
        activeDrawable.setBounds(0, 0, (int) mIndicatorSize,
                (int) mIndicatorSize);
        inactiveDrawable.setBounds(0, 0, (int) mIndicatorSize,
                (int) mIndicatorSize);
    
        int i[] = new int[2];
        i[0] = android.R.attr.textColorSecondary;
        i[1] = android.R.attr.textColorSecondaryInverse;
        TypedArray a = this.getTheme().obtainStyledAttributes(i);
    
        Shape s1 = new OvalShape();
        s1.resize(mIndicatorSize, mIndicatorSize);
        Shape s2 = new OvalShape();
        s2.resize(mIndicatorSize, mIndicatorSize);
    
        ((ShapeDrawable) activeDrawable).getPaint().setColor(
                a.getColor(0, Color.DKGRAY));
        ((ShapeDrawable) inactiveDrawable).getPaint().setColor(
                a.getColor(1, Color.LTGRAY));
    
        ((ShapeDrawable) activeDrawable).setShape(s1);
        ((ShapeDrawable) inactiveDrawable).setShape(s2);
    }
    

    希望这会有所帮助。 格力兹法比安

    【讨论】:

      【解决方案5】:

      也许其他人需要更改 XML 中的颜色,而无需像我需要的那样创建多个可绘制对象。然后制作一个不带颜色的可绘制圆,然后为 ImageView 指定 backgroundTint。

      circle.xml

      <?xml version="1.0" encoding="utf-8"?>
      <shape
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:shape="oval">
      </shape>
      

      在你的布局中:

      <ImageView
          android:layout_width="50dp"
          android:layout_height="50dp"
          android:background="@drawable/circle"
          android:backgroundTint="@color/red"/>
      

      编辑:

      有一个关于此方法的bug 阻止它在 Android Lollipop 5.0(API 级别 21)上运行。但已在较新版本中得到修复。

      【讨论】:

        【解决方案6】:
            LayerDrawable bgDrawable = (LayerDrawable) button.getBackground();
            final GradientDrawable shape = (GradientDrawable)
                    bgDrawable.findDrawableByLayerId(R.id.round_button_shape);
            shape.setColor(Color.BLACK);
        

        【讨论】:

        • round_button_shape 应该在 shape xml 文件中定义在哪里?
        【解决方案7】:

        circle.xml(可绘制)

        <?xml version="1.0" encoding="utf-8"?>
        <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        
        <solid
            android:color="#000"/>
        
        <size
            android:width="10dp"
            android:height="10dp"/>
        </shape>
        

        布局

        <ImageView
              android:id="@+id/circleColor"
              android:layout_width="15dp"
               android:layout_height="15dp"
              android:textSize="12dp"
               android:layout_gravity="center"
               android:layout_marginLeft="10dp"
              android:background="@drawable/circle"/>
        

        活动中

           circleColor = (ImageView) view.findViewById(R.id.circleColor);
           int color = Color.parseColor("#00FFFF");
           ((GradientDrawable)circleColor.getBackground()).setColor(color);
        

        【讨论】:

        • 不是一个完美的,但帮助我得到了解决方案。
        【解决方案8】:

        这个解决方案使用 android sdk v19 对我有用:

        //get the image button by id
        ImageButton myImg = (ImageButton) findViewById(R.id.some_id);
        
        //get drawable from image button
        GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();
        
        //set color as integer
        //can use Color.parseColor(color) if color is a string
        drawable.setColor(color)
        

        【讨论】:

          【解决方案9】:

          如果你有这样的 imageView:

             <ImageView
              android:id="@+id/color_button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginRight="10dp"
              android:src="@drawable/circle_color"/>
          

          给它一个可绘制的形状作为 src,你可以使用这个代码来改变形状的颜色:

          ImageView iv = (ImageView)findViewById(R.id.color_button);
          GradientDrawable bgShape = (GradientDrawable)iv.getDrawable();
          bgShape.setColor(Color.BLACK);
          

          【讨论】:

            【解决方案10】:

            我的形状 xml:

            <?xml version="1.0" encoding="utf-8"?>
            <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid  android:color="@android:color/transparent" />
            <stroke android:width="0.5dp" android:color="@android:color/holo_green_dark"/>
            </shape>
            

            我的活动 xml:

            <?xml version="1.0" encoding="utf-8"?>
            <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            tools:context="cn.easydone.test.MainActivity">
            
            <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/AppTheme.AppBarOverlay">
            
                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="?attr/colorPrimary"
                    app:popupTheme="@style/AppTheme.PopupOverlay" />
                <TextView
                    android:id="@+id/test_text"
                    android:background="@drawable/bg_stroke_dynamic_color"
                    android:padding="20dp"
                    android:text="asdasdasdasd"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
            
            </android.support.design.widget.AppBarLayout>
            
            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="10dp"
                android:clipToPadding="false"
                app:layout_behavior="@string/appbar_scrolling_view_behavior" />
            

            我的活动java:

             TextView testText = (TextView) findViewById(R.id.test_text);
             ((GradientDrawable)testText.getBackground()).setStroke(10,Color.BLACK);
            

            结果图片: result

            【讨论】:

              【解决方案11】:

              半径填充形状的最简单方法是:

              XML:

              <TextView
                  android:id="@+id/textView"
                  android:background="@drawable/test"
                  android:layout_height="45dp"
                  android:layout_width="100dp"
                  android:text="Moderate"/>
              

              Java:

              (textView.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);
              

              【讨论】:

                【解决方案12】:

                我尝试了 Ronnie 的回答,但我的应用程序崩溃了。然后我检查我的可绘制 xml。它看起来像这样:

                <selector >...</selector>
                

                。我把它改成了这个:(也改变了属性)

                <shape> ... </shape>
                

                有效。

                对于遇到同样问题的人。

                【讨论】:

                  【解决方案13】:

                  drawable_rectangle.xml

                  <?xml version="1.0" encoding="utf-8"?>
                  <shape xmlns:android="http://schemas.android.com/apk/res/android"
                      android:shape="rectangle">
                  
                      <solid android:color="@android:color/transparent" />
                  
                      <stroke
                          android:width="1dp"
                          android:color="#9f9f9f" />
                  
                      <corners
                          android:bottomLeftRadius="5dp"
                          android:bottomRightRadius="5dp"
                          android:topLeftRadius="5dp"
                          android:topRightRadius="5dp" />
                  
                  </shape>
                  

                  文本视图

                  <androidx.appcompat.widget.AppCompatTextView
                      android:id="@+id/textView"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:background="@drawable/drawable_rectangle"
                      android:gravity="center"
                      android:padding="10dp"
                      android:text="Status"
                      android:textColor="@android:color/white"
                      android:textSize="20sp" />
                  
                  
                  public static void changeRectangleColor(View view, int color) {
                      ((GradientDrawable) view.getBackground()).setStroke(1, color);
                  }    
                  
                  changeRectangleColor(textView, ContextCompat.getColor(context, R.color.colorAccent));
                  

                  【讨论】:

                    【解决方案14】:

                    您可以使用绑定适配器(Kotlin) 来实现此目的。创建一个名为 ChangeShapeColor 的绑定适配器类,如下所示

                    @BindingAdapter("shapeColor")
                    
                    // Method to load shape and set its color 
                    
                    fun loadShape(textView: TextView, color: String) {
                    // first get the drawable that you created for the shape 
                    val mDrawable = ContextCompat.getDrawable(textView.context, 
                    R.drawable.language_image_bg)
                    val  shape =   mDrawable as (GradientDrawable)
                    // use parse color method to parse #34444 to the int 
                    shape.setColor(Color.parseColor(color))
                     }
                    

                    在 res/drawable 文件夹中创建一个可绘制的形状。我创建了一个圈子

                    <shape xmlns:android="http://schemas.android.com/apk/res/android"
                    android:shape="oval" >
                    <solid android:color="#anyColorCode"/>
                    
                    <size
                        android:width="@dimen/dp_16"
                        android:height="@dimen/dp_16"/>
                    </shape>
                    

                    最后参考你的观点

                      <TextView>
                       .........
                      app:shapeColor="@{modelName.colorString}"
                     </Textview>
                    

                    【讨论】:

                      猜你喜欢
                      • 2017-01-24
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-08-11
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多