如何在Android上以编程方式修复圆角按钮?

问题描述 投票:3回答:3

我要在按钮上将圆角像下面的代码所示

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

如何用Java代码定义舍入按钮,无XML

android material-design android-button material-components material-components-android
3个回答
-1
投票

首先创建背景:

<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链接。


0
投票

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


0
投票

使用Material Components for Android

只需添加依赖项:

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

在布局中添加MaterialButton

MaterialButton

并使用方法<com.google.android.material.button.MaterialButton .... style="@style/Widget.MaterialComponents.Button.OutlinedButton" app:cornerRadius=".." app:strokeColor="@color/colorPrimary"/> 。类似于:

setCornerRadius
© www.soinside.com 2019 - 2024. All rights reserved.