我想像下面的代码一样在按钮上圆角
button.setWidth(buttonWidth);
button.setHeight(buttonHeight);
如何使用java代码定义圆角按钮,没有xml
使用 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(..);
您可以使用所需的圆角矩形背景制作一个 xml 可绘制对象(如果您希望它在按下时突出显示,请确保使用状态列表可绘制对象(并将其设置为背景。将其设置为背景只是一个 setBackgroundDrawable 调用。
只需将主题设置为材质组件即可。请注意,这会弄乱您当前的主题。
https://learntodroid.com/how-to-create-rounded-corners-for-a-button-in-android/可能是另一种选择。
首先创建一个背景:
<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));
这个答案是基于这个和这个链接。