在主题级别的RecyclerView样式

waq*_*lam 11 android listview themes styles android-recyclerview

我正在尝试RecyclerView主题级别实现通用样式参数.ListView与之相反,我使用了这样的东西:

定义了一种风格:

<style name="StyleListView" parent="Widget.AppCompat.ListView">
     <item name="android:requiresFadingEdge">vertical</item>
     <item name="android:fadingEdgeLength">10dp</item>
     <item name="android:scrollbars">vertical</item>
</style>
Run Code Online (Sandbox Code Playgroud)

后来在我的自定义主题中使用:

<item name="android:listViewStyle">@style/StyleListView</item>
Run Code Online (Sandbox Code Playgroud)

这非常适合ListView.但是,我无法反映这一点,RecyclerView因为我认为它适用于任何类型的列表.

那么,是否有任何预定义的样式属性可用于RecyclerView,例如android:recyclerViewStyle或任何东西?

如果没有,那我怎样才能在主题层面实现这一目标?

Jas*_*son 9

不幸的listViewStyleRecylerView,没有相当于.

我认为你能做的最好的事情就是为你定义一种风格RecyclerView,然后style="@style/RecyclerViewStyle"根据你的风格使用哪种视图(如果你只想在你的例子中定义一些属性).

如果你真的只是不想为每一个做那个RecyclerView,那么你必须将它子类化并defStyle在构造函数中返回一个非零参数.但是,您必须RecyclerView使用新的子类替换XML中的所有实例.


Dar*_*ish 9

主题级别的 RecyclerView 样式

RecyclerView 现在有一个默认样式属性:recyclerViewStyle,它允许在你的主题中设置默认样式

支持以下属性

    <!-- Class name of the Layout Manager to be used. -->
    <attr name="layoutManager" format="string" />
   
    <!-- ============================= -->
    <!-- Attributes for Layout Manager -->
    <!-- ============================= -->
    <attr name="android:orientation" />
    <attr name="android:descendantFocusability" />
    <attr name="android:clipToPadding" />
    <attr name="spanCount" format="integer"/>
    <attr name="reverseLayout" format="boolean" />
    <attr name="stackFromEnd" format="boolean" />
    <attr name="fastScrollEnabled" format="boolean" />
    <attr name="fastScrollVerticalThumbDrawable" format="reference" />
    <attr name="fastScrollVerticalTrackDrawable" format="reference" />
    <attr name="fastScrollHorizontalThumbDrawable" format="reference" />
    <attr name="fastScrollHorizontalTrackDrawable" format="reference" />
Run Code Online (Sandbox Code Playgroud)

要使用上述功能,请在 build.gradle 文件中添加/更新以下依赖项。

dependencies {
    implementation 'androidx.recyclerview:recyclerview:1.1.0-beta05'
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到提交。

例子:

1. 定义您的默认样式

<style name="DefaultRecyclerViewStyle">

    <item name="layoutManager">androidx.recyclerview.widget.GridLayoutManager</item>
    <item name="android:orientation">vertical</item>
    <item name="spanCount">2</item>

</style>
Run Code Online (Sandbox Code Playgroud)

2.将上述样式添加到您的默认主题中

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="recyclerViewStyle">@style/DefaultRecyclerViewStyle</item>
</style>
Run Code Online (Sandbox Code Playgroud)

就这样。您已经为 RecyclerView 小部件定义了应用程序范围的默认样式。