【问题标题】:How to tint Button using the Latest AppCompat如何使用最新的 AppCompat 为按钮着色
【发布时间】:2016-07-06 10:19:47
【问题描述】:

我需要知道使用最新的 AppCompat(目前为 23.2.1)为材质按钮 (AppCompatButton) 着色的最佳(和推荐)方法是什么。我从来没有想过会如此令人沮丧!我尝试了来自here 的大部分答案,但它们要么不起作用,要么得到了意想不到的结果。

我需要保持对 api >= 9 的向后兼容性并且只需要将涟漪效果应用于 >=21 没什么特别的。那么到目前为止最好的方法是什么?

如果您能同时提供 xml 和 java 代码,我将不胜感激。

【问题讨论】:

    标签: android android-button android-appcompat


    【解决方案1】:

    有很多方法可以做到这一点。 我最喜欢的是:

    <Button
     android:id="@+id/activity_main_some_button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     style="@style/Widget.AppCompat.Button.Colored"
     android:text="This is a button" />  
    

    这会自动使用您(希望)在主题中设置的强调色为按钮着色,同时保持 API = Lollipop 的按下状态。

    如果没有其他方法,您可以自己为按钮着色:

    AppCompatButton myExampleButton = new AppCompatButton(getContext());
    
    myExampleButton.setSupportBackgroundTintList(ContextCompat.getColorStateList(getContext(),
                                                 R.color.some_color));
    

    更新

    您可以执行以下操作来使用自定义颜色:

    <style name="MyButtonTheme" parent="Widget.AppCompat.Button.Colored">
        <item name="colorButtonNormal">@color/someColor</item>
    </style>
    

    使用所需颜色定义新样式。

    <Button
     android:id="@+id/activity_main_some_button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:theme="@style/MyButtonTheme"
     android:text="This is a button" />
    

    将其设置为您的按钮。

    【讨论】:

    • 我不想使用强调色。只是一些随意的颜色。如何从 xml 中做到这一点?
    猜你喜欢
    • 2015-08-20
    • 2014-12-18
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2019-10-03
    相关资源
    最近更新 更多