android AppCompatButton 设置背景图片

文章目录

    遇到一个奇怪的问题,在 Android 项目中给 Button 设置背景图片,总是不生效。

    <Button
    	android:background="@drawable/normal"
    	android:text="OK">
    </Button>
    

    改用 androidx.appcompat.widget.AppCompatButton

    <androidx.appcompat.widget.AppCompatButton
    	android:background="@drawable/normal"
    	android:text="OK">
    </androidx.appcompat.widget.AppCompatButton>
    

    就可以了。

    AppCompatButton 禁用字母全大写

    但是 AppCompatButton 相对 Button 有个问题,就是按钮中的字母被默认自动转换成了大写。

    恢复原始字母的方式:

    android:textAllCaps="false"
    

    换成新 AppCompatButton 后,icon 没有了

    <androidx.appcompat.widget.AppCompatButton
    	app:icon="@drawable/ok"
    	app:iconGravity="textStart"
    	android:background="@drawable/normal"
    	android:text="OK">
    </androidx.appcompat.widget.AppCompatButton>
    

    https://www.qiniu.com/qfans/qnso-40357039

    android:drawableStart="@drawable/balance"
    

    这个可以,但是大小默认不合适,需要自己控制。

    <androidx.appcompat.widget.AppCompatButton
    	android:paddingHorizontal="30dp"
    	android:drawableLeft="@drawable/ok2"
    	android:background="@drawable/normal"
    	android:text="OK">
    </androidx.appcompat.widget.AppCompatButton>
    

    这里新建一个 drawable 文件,将原始图片封装。

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item
        android:drawable="@drawable/ok"
        android:width="@dimen/icon_size"
        android:height="@dimen/icon_size"
        />
    
    </layer-list >
    

    dimens.xml

    <resources>
        <dimen name="icon_size">20dp</dimen>
    </resources>
    

    AppCompatButton 与 Button 的区别

    https://stackoverflow.com/questions/69283849/what-is-the-difference-between-button-and-androidx-appcompat-widget-appcompatbut

    An AppCompatButton is simply a Button which supports compatible features on older versions of the platform

    去掉阴影

    android:stateListAnimator="@null"
    

    参考

    https://stackoverflow.com/questions/68423729/is-there-anyway-to-change-background-image-not-color-of-button-from-xml-in-and

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式