MultipleTheme框架兼容RecyclerView和CardView&RecyclerView缓存机制

一.引言

最近搞了搞app无缝切换主题功能,github上看了看,流行的还是插件式,好吧。。完了研究下了。

不过今天咱要搞的是MultipleTheme这个框架,也有1000多star了,应该可以吧,于是乎ji动的整到项目里准备大干一场。。。小弟沉默十分钟后,纳尼?要全部重写用到的view?!而且没有兼容RecyclerView,CardView。。。看来不维护了,行吧行吧,既然这样那就当学习了,顺便咱给他兼容一下。于是乎,有了本文~

附上框架地址:https://github.com/dersoncheng/MultipleTheme

具体使用github上作者写的很清楚,这里就不多说了。

本文内容:1.此框架技术点。

    2.从源码分析RecyclerView缓存机制。

3.此框架如何兼容RecyclerView和CardView。

二.框架技术点

1.框架调用流程:

1.调用ColorUiUtil类中changeTheme(View view,Theme theme) :通过递归方式,从参数view开始遍历其所有子view,如果遍历到的view继承了ColorUiInterface接口,那么调用其实现的接口方法。

 public static void changeTheme(View rootView, Resources.Theme theme) {
        if (rootView instanceof ColorUiInterface) {
            ((ColorUiInterface) rootView).setTheme(theme);
            if (rootView instanceof ViewGroup) {
                int count = ((ViewGroup) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }
            if (rootView instanceof AbsListView) {
                try {
                    Field localField = AbsListView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));
                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                } catch (NoSuchMethodException e3) {
                    e3.printStackTrace();
                } catch (IllegalAccessException e4) {
                    e4.printStackTrace();
                } catch (InvocationTargetException e5) {
                    e5.printStackTrace();
                }
            }
        } else {
            if (rootView instanceof ViewGroup) {
                int count = ((ViewGroup) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }
            if (rootView instanceof AbsListView) {
                try {
                    Field localField = AbsListView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));
                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                } catch (NoSuchMethodException e3) {
                    e3.printStackTrace();
                } catch (IllegalAccessException e4) {
                    e4.printStackTrace();
                } catch (InvocationTargetException e5) {
                    e5.printStackTrace();
                }
            }
        }
    }

2.实现的接口方法,会根据需要改变的属性调用ViewAttributeUtil类中的各种方法。

如applyBackgroundDrawable(Context,Theme,attrId):最后这个方法会根据Theme获取到对应的drawable,调用这个view的setBackGroundDrawable()方法实现设置背景。

public static void applyBackgroundDrawable(ColorUiInterface ci, Resources.Theme theme, int paramInt) {
        TypedArray ta = theme.obtainStyledAttributes(new int[]{paramInt});
        Drawable drawable = ta.getDrawable(0);
        if (null != ci) {
            (ci.getView()).setBackgroundDrawable(drawable);
        }
        ta.recycle();
    }

3.上面applyBackgroundDrawable(Context,Theme,attrId)方法中第三个参数attrid,又是从ViewAttributeUtil类中getBackGroundAttribute(AttributeSet)得到的:

public static int getBackgroundAttibute(AttributeSet attr) {
        return getAttributeValue(attr, android.R.attr.background);
    }
public static int getAttributeValue(AttributeSet attr, int paramInt) {
        int value = -1;
        int count = attr.getAttributeCount();
        for (int i = 0; i < count; i++) {
            if (attr.getAttributeNameResource(i) == paramInt) {
                String str = attr.getAttributeValue(i);
                if (null != str && str.startsWith("?")) {
                    value = Integer.valueOf(str.substring(1, str.length())).intValue();
                    return value;
                }
            }
        }
        return value;
    }

2.清空listView缓存,做到listView所有item都成功改变theme

 public static void changeTheme(View rootView, Resources.Theme theme) {
        if (rootView instanceof ColorUiInterface) {
            ((ColorUiInterface) rootView).setTheme(theme);
            if (rootView instanceof ViewGroup) {
                int count = ((ViewGroup) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }
            if (rootView instanceof AbsListView) {
                try {
                    Field localField = AbsListView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));
                } catch 。。。省略异常
            }
        } else {
            if (rootView instanceof ViewGroup) {
                int count = ((ViewGroup) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }
            if (rootView instanceof AbsListView) {
                try {
                    Field localField = AbsListView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));
                } catch<span style="font-family: Arial, Helvetica, sans-serif;">。。。省略异常</span>
            }
        }
    }
咱们看上面这个重要的方法: 由于ListView也是ViewGroup,并有缓存机制,在换肤后会有缓存的item再次被复用时,此项item没有改变them e。就会出现当前可见item换了主题,滑动列表,之前不可见的有一部分item的theme没有发生变化。
于是这方法,通过反射调用了缓存管理类内部类——RecyclerBin中clear()方法,清空所有item,让listview将所有item重新创建一遍。
那根据这个原理,将RecyclerView中缓存做一下清空。下面先介绍一下RecyclerView缓存机制和兼容。

三.RecyclerView缓存机制

1.RecyclerView缓存机制

RecyclerView中也有管理缓存的内部类:Recycler。LayoutManager获取Adapter某一项的View时会调用Recycler中的方法获取。
2.如下是Recyler的几个关键成员变量和方法:

private ArrayList<ViewHolder> mAttachedScrap :未与RecyclerView分离的ViewHolder列表。 

private ArrayList<ViewHolder> mChangedScrap: 分离的ViewHolder列表。

private ArrayList<ViewHolder> mCachedViews: ViewHolder缓存列表。会默认缓存

private ViewCacheExtension mViewCacheExtension: 开发者可以控制的ViewHolder缓存。

private RecycledViewPool mRecyclerPool: 提供复用ViewHolder池。

public void bindViewToPosition(View view, int position) :将某个View绑定到Adapter的某个位置。

public View getViewForPosition(int position):LayoutManager通过此方法获取某一项的view。

3.LayoutManager会通过其中getViewForPosition方法获取缓存的view:获取缓存view顺序是:  

(1)mChangedScrap查找,若匹配到则返回相应holder  

(2)mAttachedScrap查找,若匹配到且holder有效则返回相应holder  

(3)mViewCacheExtension查找,若匹配到则返回相应holder  

(4)mRecyclerPool中查找,若匹配到则返回相应holder  

(5)还是没有匹配的,那么adapter.createViewHolder(),创建新的holder  

(6)返回holder.itemView


四.此框架如何兼容RecyclerView和CardView。

   1.兼容RecyclerView

为了保证改变所有item的theme,所以要情况缓存。那么从上面缓存机制知道,我们需要把 mAttachedScrap ,mChangedScrap,mCachedViews,mViewCacheExtension,mRecyclerPool中的缓存都清空掉。
在Recycler类中有三个方法可以清空数据:
(1)clear()
(2)clearScrap()
(3)RecycledViewPool中的clear()
兼容后的ColorUiUtil类:
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class ColorUiUtil {
    
    public static void changeTheme(View rootView, Resources.Theme theme) {
        if (rootView instanceof ColorUiInterface) {
            ((ColorUiInterface) rootView).setTheme(theme);

            if (rootView instanceof RecyclerView) {
                int count = ((RecyclerView) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }
            else if (rootView instanceof ViewGroup) {
                int count = ((ViewGroup) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }

            if (rootView instanceof AbsListView) {
                try {
                    Field localField = AbsListView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));
                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                } catch (NoSuchMethodException e3) {
                    e3.printStackTrace();
                } catch (IllegalAccessException e4) {
                    e4.printStackTrace();
                } catch (InvocationTargetException e5) {
                    e5.printStackTrace();
                }
            } else if (rootView instanceof RecyclerView) {
                try {
              
                    Field localField = RecyclerView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.support.v7.widget.RecyclerView$Recycler").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));

                    Method localMethod1 = Class.forName("android.support.v7.widget.RecyclerView$Recycler").getDeclaredMethod("clearScrap");
                    localMethod1.setAccessible(true);
                    localMethod1.invoke(localField.get(rootView));

                    ((RecyclerView) rootView).getRecycledViewPool().clear();

                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                } catch (NoSuchMethodException e3) {
                    e3.printStackTrace();
                } catch (IllegalAccessException e4) {
                    e4.printStackTrace();
                } catch (InvocationTargetException e5) {
                    e5.printStackTrace();
                }
            }
        } else {
            if (rootView instanceof RecyclerView) {
                int count = ((RecyclerView) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }
            else if (rootView instanceof ViewGroup) {
                int count = ((ViewGroup) rootView).getChildCount();
                for (int i = 0; i < count; i++) {
                    changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
                }
            }

            if (rootView instanceof AbsListView) {
                try {
                    Field localField = AbsListView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));
                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                } catch (NoSuchMethodException e3) {
                    e3.printStackTrace();
                } catch (IllegalAccessException e4) {
                    e4.printStackTrace();
                } catch (InvocationTargetException e5) {
                    e5.printStackTrace();
                }
            } else if (rootView instanceof RecyclerView) {
                try {
                   
                    Field localField = RecyclerView.class.getDeclaredField("mRecycler");
                    localField.setAccessible(true);
                    Method localMethod = Class.forName("android.support.v7.widget.RecyclerView$Recycler").getDeclaredMethod("clear");
                    localMethod.setAccessible(true);
                    localMethod.invoke(localField.get(rootView));

                    Method localMethod1 = Class.forName("android.support.v7.widget.RecyclerView$Recycler").getDeclaredMethod("clearScrap");
                    localMethod1.setAccessible(true);
                    localMethod1.invoke(localField.get(rootView));

                    ((RecyclerView) rootView).getRecycledViewPool().clear();

                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                } catch (NoSuchMethodException e3) {
                    e3.printStackTrace();
                } catch (IllegalAccessException e4) {
                    e4.printStackTrace();
                } catch (InvocationTargetException e5) {
                    e5.printStackTrace();
                }
            }
        }
    }
}

3.兼容CardView

cardView设置其背景颜色有自己的方法:
setCardBackgroundColor(Color)
xml中:app:cardBackgroundColor="?attr/colorPrimaryDark"
因为CardView继承自FrameLayout,所以也可以用setBackGroundDrawable(),但是测试下,在列表中,会出现更改theme无效的bug。
框架中做如下修改:
(1)在ViewAttributeUtil类中增加一个方法:
public static int getCardViewAttribute(AttributeSet attributeSet) {
        return getAttributeValue(attributeSet, android.support.v7.cardview.R.attr.cardBackgroundColor);
    }
(2 在ViewAttributeUtil类中增加一个方法:
public static void applyCardViewBackgroundColor(ColorUiInterface ci, Resources.Theme theme, int paramInt) {
    TypedArray ta = theme.obtainStyledAttributes(new int[]{paramInt});
    int color = ta.getColor(0, Color.GREEN);
    if (null != ci) {
        ((CardView)ci.getView()).setCardBackgroundColor(color);
    }
    ta.recycle();
}
(3)在自定义ColorCardView类中,调用的就是上面两个方法了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我很乐意回答您的问题。首先,RecyclerView 是一个强大的视图组件,用于显示大量数据集合。它可以高效地管理和显示列表、网格和瀑布流等多种样式的布局。而 CardView 则是一个 Material Design 风格的容器视图,用于显示单个数据项的卡片式布局。 在 Android 中使用 RecyclerViewCardView 需要先在 build.gradle 文件中添加依赖库: ```groovy dependencies { implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0' } ``` 接下来,在布局文件中声明 RecyclerViewCardView: ```xml <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:padding="@dimen/default_padding" android:scrollbarStyle="outsideOverlay" android:scrollbars="vertical" /> <android.support.v7.widget.CardView android:id="@+id/cardview" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardCornerRadius="@dimen/default_corner_radius" app:cardElevation="@dimen/default_elevation" app:cardUseCompatPadding="true"> <!-- 在 CardView 中添加需要显示的内容 --> </android.support.v7.widget.CardView> ``` 最后,在代码中使用 RecyclerViewCardView: ```java RecyclerView recyclerView = findViewById(R.id.recyclerview); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new MyAdapter()); CardView cardView = findViewById(R.id.cardview); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 处理点击事件 } }); ``` 其中,MyAdapter 是一个自定义的适配器类,用于管理和显示数据集合。在该类中,需要实现 onCreateViewHolder、onBindViewHolder 和 getItemCount 等方法,以便正确地显示数据项。 总之,RecyclerViewCardViewAndroid 中常用的界面组件,它们可以帮助我们高效地显示列表和卡片式布局。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值