【问题标题】:How to programmatically round corners and set random background colors如何以编程方式圆角并设置随机背景颜色
【发布时间】:2013-08-25 20:32:21
【问题描述】:

我想对视图的角进行圆角处理,并在运行时根据内容更改视图的颜色。

TextView v = new TextView(context);
v.setText(tagsList.get(i));
if(i%2 == 0){
    v.setBackgroundColor(Color.RED);
}else{
    v.setBackgroundColor(Color.BLUE);
}

v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
v.setPadding(twoDP, twoDP, twoDP, twoDP);               
v.setBackgroundResource(R.drawable.tags_rounded_corners);

我希望设置可绘制对象和颜色会重叠,但事实并非如此。无论我第二次执行哪个都是生成的背景。

有没有办法以编程方式创建这个视图,记住背景颜色要到运行时才会决定?

编辑:我现在只是在红色和蓝色之间交换以进行测试。稍后颜色将由用户选择。

编辑:

tags_rounded_corners.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners 
         android:bottomRightRadius="2dp" 
         android:bottomLeftRadius="2dp" 
         android:topLeftRadius="2dp" 
         android:topRightRadius="2dp"/>
</shape>

【问题讨论】:

  • 当然背景颜色和背景图片会相互覆盖。你想达到什么目的? tags_rounded_corners 是什么?
  • 您能显示更多代码吗?它看起来不错,所以我想知道您可以使用某种 listView,或者重用现有的 textview。

标签: android android-layout background android-view rounded-corners


【解决方案1】:

检索背景可绘制对象并设置其颜色,而不是 setBackgroundColor

v.setBackgroundResource(R.drawable.tags_rounded_corners);

GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
  drawable.setColor(Color.RED);
} else {
  drawable.setColor(Color.BLUE);
}

此外,您可以在 tags_rounded_corners.xml 中定义填充:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="4dp" />
  <padding
    android:top="2dp"
    android:left="2dp"
    android:bottom="2dp"
    android:right="2dp" />
</shape> 

【讨论】:

  • 完美答案!它也适用于冲击,但我们可以使用类似 colorDrawable = resources.getDrawable(R.drawable.x_sd_circle); colorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);如果我们没有边界。但是如果有边框,你能告诉我 PorterDuff.Mode,这样笔触颜色就不会改变
  • 如何通过 XML 添加背景颜色?
  • 如果 "v" 是 TextView 而不是 v.getBackground() 将转换 "java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.GradientDrawable" 是这真的可以追溯到 13 年吗?
  • @sonavolob 你是对的。它给出了 ClassCastException
  • 完美解决方案!谢谢!
【解决方案2】:

设置圆角和向视图添加随机背景颜色的总体编程方法。 我没有测试过代码,但你明白了。

 GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
  shape.setColor(Color.RED);
 } else {
  shape.setColor(Color.BLUE);
 }

 // now find your view and add background to it
 View view = (LinearLayout) findViewById( R.id.my_view );
 view.setBackground(shape);

这里我们使用渐变绘制,以便我们可以使用GradientDrawable#setCornerRadius,因为ShapeDrawable 不提供任何此类方法。

【讨论】:

  • shape.setCornerRadii(corners);它非常有用
  • 考虑使用PaintDrawable 而不是GradientDrawable。它支持圆角和一种似乎比渐变更合适的颜色。
  • 这很好用!我在 Xamarin 中使用它。 var pd = new PaintDrawable(BackgroundColor); pd.SetCornerRadius(15); myView.Background = pd;
  • 不错的快速解决方案,但请注意它需要 API 最低级别 16
  • @Anonymous-E 我建议你查找GradientDrawable.setCornerRadii() 函数。
【解决方案3】:

如果你没有中风,你可以使用

colorDrawable = resources.getDrawable(R.drawable.x_sd_circle); 

colorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);

但这也会改变笔触颜色

【讨论】:

  • 我打算用这个,但我中风了。
【解决方案4】:

我认为最快的方法是:

GradientDrawable gradientDrawable = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction 
            new int[] {0xFF757775,0xFF151515}); //set the color of gradient
gradientDrawable.setCornerRadius(10f); //set corner radius

//Apply background to your view
View view = (RelativeLayout) findViewById( R.id.my_view );
if(Build.VERSION.SDK_INT>=16)
     view.setBackground(gradientDrawable);
else view.setBackgroundDrawable(gradientDrawable);    

【讨论】:

    【解决方案5】:

    您可以像这样使用DrawableCompat 更好地实现它:

    Drawable backgroundDrawable = view.getBackground();             
    DrawableCompat.setTint(backgroundDrawable, newColor);
    

    【讨论】:

      【解决方案6】:

      您可以动态更改任何项目(布局、文本视图)的颜色。尝试下面的代码在布局中以编程方式设置颜色

      在activity.java文件中

      
      String quote_bg_color = "#FFC107"
      quoteContainer= (LinearLayout)view.findViewById(R.id.id_quotecontainer);
      quoteContainer.setBackgroundResource(R.drawable.layout_round);
      GradientDrawable drawable = (GradientDrawable) quoteContainer.getBackground();
      drawable.setColor(Color.parseColor(quote_bg_color));
      
      

      在drawable文件夹中创建layout_round.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <shape xmlns:android="http://schemas.android.com/apk/res/android">
          <solid android:color="@color/colorPrimaryLight"/>
          <stroke android:width="0dp" android:color="#B1BCBE" />
          <corners android:radius="10dp"/>
          <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
      </shape>
      
      

      activity.xml 文件中的布局

      <LinearLayout
              android:id="@+id/id_quotecontainer"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">
      
      ----other components---
      
      </LinearLayout>
      
      
      

      【讨论】:

        【解决方案7】:

        这是一个使用扩展的示例。 这假设视图具有相同的宽度和高度。

        需要使用布局更改监听器来获取视图大小。 然后你可以在这样的视图上调用它myView.setRoundedBackground(Color.WHITE)

        fun View.setRoundedBackground(@ColorInt color: Int) {
            addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
                override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
        
                    val shape = GradientDrawable()
                    shape.cornerRadius = measuredHeight / 2f
                    shape.setColor(color)
        
                    background = shape
        
                    removeOnLayoutChangeListener(this)
                }
            })
        }
        

        【讨论】:

          【解决方案8】:

          将@cimlman 的comment 复制到顶级答案中以获得更多可见性:

          PaintDrawable(Color.CYAN).apply {
            setCornerRadius(24f)
          }
          

          仅供参考:ShapeDrawable(及其子类型 PaintDrawable)使用默认的固有宽度和高度 0。如果可绘制对象未显示在您的用例中,您可能需要手动设置尺寸:

          PaintDrawable(Color.CYAN).apply {
            intrinsicWidth = -1
            intrinsicHeight = -1
            setCornerRadius(24f)
          }
          

          -1 是一个神奇的常数,表示 Drawable 没有自己的固有宽度和高度 (Source)。

          【讨论】:

            【解决方案9】:

            因为问题已经回答了。但我有一点调整

            GradientDrawable drawable = (GradientDrawable) ContextCompat.getDrawable(context, R.drawable.YOUR_DRAWABLE).mutate();
            

            你可以改变圆角半径:

            drawable.setCornerRadius(YOUR_VALUE);
            

            改变颜色:

            drawable.setColor(Color.YOUR_COLOR);
            

            一个可变的drawable保证不与任何其他drawable共享它的状态。因此,如果您在不使用 mutate() 的情况下更改半径,您也可能会更改其他状态。它最适合特定视图。

            最后别忘了设置drawable。

            this.setBackground(drawable);
            

            【讨论】:

              猜你喜欢
              • 2021-10-18
              • 2023-03-26
              • 1970-01-01
              • 2014-06-24
              • 2021-05-20
              • 2015-11-20
              • 1970-01-01
              • 1970-01-01
              • 2011-06-13
              相关资源
              最近更新 更多