今天看了一篇博客,就是分析平常我们给Button或TextView设置带圆角背景,大部分做法都是使用shape,然后shape有它的局限性,角度,填充色都是固定的,假如有多个不同角度的,就需要对应多份shape。据我了解网上也有第三方实现的动态改变背景的三方库,也能很友好的随意设置背景,因为项目使用了Material,恰巧也看到里面有自带的实现。
Material依赖库
implementation ‘androidx.multidex:multidex:2.0.1’
1、MaterialButton
MaterialButton 继承自Button,里面实现了圆角,边框,水波纹的点击效果,同时也可以设置icon,类似于View的DrawableLeft和DrawableTop,不过它的设置更灵活
<com.google.android.material.button.MaterialButton
android:layout_width="match_parent"
mine:backgroundTint="@color/flow_color_orange"
android:text="显示文本"
mine:icon="@mipmap/ic_add"
mine:iconGravity="textStart"
mine:iconTint="@color/main_color"
android:visibility="visible"
android:layout_marginLeft="@dimen/dp_24"
android:layout_marginRight="@dimen/dp_24"
android:layout_marginTop="@dimen/dp_12"
mine:rippleColor="@color/main_red"
android:insetTop="@dimen/dp_0"
android:insetBottom="@dimen/dp_0"
app:cornerRadius="@dimen/dp_22"
android:layout_height="@dimen/dp_44"/>
效果
iconGravity设施icon的显示位置 textStart textEnd 、end和start四个模式
backgroundTint 设置背景色
insetTop 顶部内边距
cornerRadius 设置角度
以及其他的strokeWidth,strokeColor设置边框、颜色
2、ShapeableImageView
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="@dimen/dp_70"
android:id="@+id/iv_head_2"
android:src="@mipmap/ic_launcher"
android:layout_height="@dimen/dp_70"/>
在代码里面,通过构建一个ShapeAppearanceModel对象,从而改变ImageVIew的属性
ShapeAppearanceModel model = ShapeAppearanceModel.builder()
.setTopLeftCornerSize(12f)
.setTopRightCornerSize(12f)
.setBottomLeftCornerSize(0f)
.setBottomRightCornerSize(0f)
// .setAllCornerSizes(0f)
// .setAllCornerSizes(ShapeAppearanceModel.PILL)
.build();
iv_head_2.setShapeAppearanceModel(model);
该控件默认有个圆角,想去掉直接setAllCornerSizes为 0
另外设置为ShapeAppearanceModel.PILL,可直接圆形
同样也可设置边框和边框颜色,属性也可在style中统一设置,上面是我们常用到的功能
注意使用Material时得继承它的主题样式,不然app会崩溃
<style name="MaterialComponents_Theme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customize your theme here. -->
...
</style>
然后再Application标签下应用该主题
更多使用,参考博客