【问题标题】:Styleable round Button可设计的圆形按钮
【发布时间】:2015-02-18 00:03:18
【问题描述】:

创建圆形按钮有很多很好的解决方案。 (How to make a round button?)

然而,其中大多数似乎在按钮 xml 文件中硬编码颜色。

有没有办法创建一个具有可配置/可样式颜色的圆形按钮? (我不喜欢为我可能使用的每个颜色按钮创建一个 xml 文件的想法)

理想情况下,我会在 layout.xml 中使用 RoundButton 时应用颜色,例如视图。

注意:我的Button需要包含文本,所以也可以是TextView。

谢谢

【问题讨论】:

    标签: android xml button widget


    【解决方案1】:

    定义没有颜色的xml(来自您的链接的xml):

    roundedbutton.xml:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:bottomRightRadius="8dip"
        android:bottomLeftRadius="8dip"
        android:topRightRadius="8dip"
        android:topLeftRadius="8dip"/>
    

    button.xml:

    <Button
       android:layout_height="50dp"
        android:layout_width="90dp"
        android:id="@+id/button"
        android:text="Button"
        android:background="@drawable/roundedbutton"/>
    

    你可以这样做:

     button.getBackground().setColorFilter(Color.parseColor("#bbe618"), PorterDuff.Mode.SRC_IN);
    

    结果:

    【讨论】:

    • 很好,谢谢,我使用了 android:shape="oval"> 效果很好
    【解决方案2】:

    如果你想要一个简单的圆角按钮,你可以直接使用 CardView 从这里:round corners。您可以通过编程方式设置 CardView 背景颜色并使用其前景=?selectableitembackground 保持波纹

    对于圆形按钮,您可以使用这个库:circle button

    【讨论】:

      【解决方案3】:

      你可以创建一个这样的函数,并将视图和颜色传递给它。

      /**
       * 
       * @param v: Can be any view like Button, Textview, Linearlayout,etc
       * @param color: Background color which you want
       */
      public static void setRoundedBackGround(View v, int color)
      {
          GradientDrawable drawable = new GradientDrawable();
          drawable.setShape(GradientDrawable.RING);
          drawable.setStroke(3, Color.BLACK); // You can set any border color 
      
          if(color == 0)
          {
              drawable.setColor(Color.TRANSPARENT);
              v.setBackgroundDrawable(drawable);
          }
          else
          {
              drawable.setColor(color);
              v.setBackgroundDrawable(drawable);
          }
      }
      

      希望这对你有帮助。

      【讨论】:

        猜你喜欢
        • 2011-06-18
        • 2012-08-28
        • 2021-09-15
        • 2013-12-27
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        相关资源
        最近更新 更多