我要在按钮上将圆角像下面的代码所示
button.setWidth(buttonWidth);
button.setHeight(buttonHeight);
如何用Java代码定义舍入按钮,无XML
首先创建背景:
<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));
您将使用所需的圆角矩形背景制作xml可绘制(如果要在按下时使其亮起,请确保使用状态列表可绘制,并将其设置为背景。将其设置为背景只是一个setBackgroundDrawable调用。
使用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