【问题标题】:How to fix programmatically round corners buttons on android?如何以编程方式修复android上的圆角按钮?
【发布时间】:2019-10-27 11:12:49
【问题描述】:

我要像下面的代码那样在按钮上圆角

        button.setWidth(buttonWidth);
        button.setHeight(buttonHeight);

如何用java代码定义圆形按钮,没有xml

【问题讨论】:

    标签: android material-design android-button material-components material-components-android


    【解决方案1】:

    使用Material Components for Android

    只需添加依赖即可:

    implementation ‘com.google.android.material:material:1.0.0’
    

    在你的布局中添加MaterialButton

    <com.google.android.material.button.MaterialButton
       ....
       style="@style/Widget.MaterialComponents.Button.OutlinedButton"
       app:cornerRadius=".."
       app:strokeColor="@color/colorPrimary"/>
    

    并使用方法setCornerRadius
    比如:

    button.setCornerRadius(..);
    

    【讨论】:

      【解决方案2】:

      您将使用所需的圆角矩形背景制作一个 xml 可绘制对象(如果您希望它在按下时高亮,请确保使用可绘制的状态列表)并将其设置为背景。将其设置为背景只是一个 setBackgroundDrawable 调用。

      【讨论】:

      • 我确实喜欢这个“button.setBackground(R.drawable.score_background);”但没有应用
      【解决方案3】:

      首先创建一个背景:

      <selector xmlns:android="http://schemas.android.com/apk/res/android" >
      <item android:state_pressed="true" >
          <shape android:shape="rectangle"  >
              <corners android:radius="3dip" />
              <stroke android:width="1dip" android:color="#5e7974" />
              <gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92"  />            
          </shape>
      </item>
      <item android:state_focused="true">
          <shape android:shape="rectangle"  >
              <corners android:radius="3dip" />
              <stroke android:width="1dip" android:color="#5e7974" />
              <solid android:color="#58857e"/>       
          </shape>
      </item>  
      <item >
         <shape android:shape="rectangle"  >
              <corners android:radius="3dip" />
              <stroke android:width="1dip" android:color="#5e7974" />
              <gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />            
         </shape>
      </item>
      

      然后:

      button.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
      

      此答案基于thisthis 链接。

      【讨论】:

        猜你喜欢
        • 2015-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-06-04
        • 2021-01-31
        • 1970-01-01
        • 2014-01-10
        • 2011-05-29
        • 2014-10-16
        相关资源
        最近更新 更多