android - 如何在自定义复选框 View 上保留支持库复选框的样式?

标签 android checkbox android-support-library android-styles

背景

我为我的应用程序使用支持库的“Theme.AppCompat.NoActionBar”主题。

问题

事情是,我使用了一个自定义的 Checkbox(一个扩展“CheckBox”的类),出于某种原因我没有得到与 native 相同的样式,即使它的代码不应该改变任何东西,即使 UI 设计器表明它没问题。

这是显示该情况的屏幕截图。

界面设计师:

enter image description here

Android Kitkat 设备: enter image description here

这是 XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center"
              android:orientation="vertical"
              tools:context=".MainActivity">

    <CheckBox
        android:layout_width="wrap_content"
        android:text="Native Checbox"
        android:layout_height="wrap_content"
        android:checked="false"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:text="Native Checbox checked"
        android:layout_height="wrap_content"
        android:checked="true"/>

    <lb.test.CheckBox
        android:layout_width="wrap_content"
        android:text="Customized Checbox"
        android:layout_height="wrap_content"
        android:checked="false"/>

    <lb.test.CheckBox
        android:layout_width="wrap_content"
        android:text="Customized Checbox checked"
        android:layout_height="wrap_content"
        android:checked="true"/>
</LinearLayout>

我更喜欢用于原生复选框的普通样式。

为简单起见,我已将此测试尽可能地精简,您只需为自定义复选框添加 CTOR,使其与普通复选框几乎相同。

问题

我应该如何克服这种奇怪的行为?为什么 UI 设计人员不能展示这种简单案例的真实展示方式?

是否还有其他我应该了解的具有这种行为的 View ?

最佳答案

根据 AppCompat v21 blog post关于小部件着色:

When running on devices with Android 5.0, all of the widgets are tinted using the color theme attributes we just talked about. There are two main features which allow this on Lollipop: drawable tinting, and referencing theme attributes (of the form ?attr/foo) in drawables.

AppCompat provides similar behaviour on earlier versions of Android for a subset of UI widgets:

Everything provided by AppCompat’s toolbar (action modes, etc)

不幸的是,它的一个局限性是只有当您在 XML 文件中使用这些类而不是子类时才会这样做。例如您的 lb.test.CheckBox。该帖子的常见问题解答中有一条说明“这可能会在未来发生变化。”,但目前尚未发布任何内容。

关于android - 如何在自定义复选框 View 上保留支持库复选框的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27573977/

相关文章:

wpf - 如何防止在第一次单击时选择整个DataGrid行?

c# - 在复选框上选中相应的表之间传输数据

安卓支持工具栏 : Resizing won't realign menu items

android - 调用 MenuItem.collapseActionView 时出现 NoSuchMethodError

android - 通过 thread_id 取得联系

android - 三星 KNOX 兼容应用程序

java - Android Studio 无法识别自定义 View 类

C# Checkedlistbox 如果选中

android - 当应用程序切换到后台时,我的 android 位置服务被杀死

android - 如何将页脚添加到 NavigationView - Android 支持设计库?