文章目录
一、报错信息
二、错误分析
三、修改方案
一、报错信息
之前开发 TabLayout 使用的是 com.android.support:design:25.3.1 支持库 ,
implementation 'com.android.support:design:25.3.1'
现在升级到 28.0.0 28.0.028.0.0 ;
implementation 'com.android.support:design:28.0.0'
报错信息 :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.lang.reflect.Field.setAccessible(boolean)' on a null object reference
二、错误分析
在老版本的 TabLayout 中无法拿到 TabLayout 中的 Tab 组件信息 , 需要通过反射获取 , 在 TabLayout.Tab 中的组件是 mView 成员 , 反射获取其 mView 成员即可 ;
TabLayout.Tab tab = tabLayout.getTabAt(i); Field mViewField = null; try { mViewField = TabLayout.Tab.class.getDeclaredField("mView"); } catch (NoSuchFieldException e) { e.printStackTrace(); } mViewField.setAccessible(true); try { View mView = (View) mViewField.get(tab); } catch (IllegalAccessException e) { e.printStackTrace(); }
本次报错后 , 查询源码 , 发现 Google 对 TabLayout.Tab 源码进行了修改 , 没有 mView 成员 , 肯定反射不到相关成员变量 , 因此报错 ;
public class TabLayout extends HorizontalScrollView { public static class Tab { public static final int INVALID_POSITION = -1; private Object tag; private Drawable icon; private CharSequence text; private CharSequence contentDesc; private int position = -1; private View customView; public TabLayout parent; public TabLayout.TabView view; public Tab() { } @Nullable public Object getTag() { return this.tag; } @NonNull public TabLayout.Tab setTag(@Nullable Object tag) { this.tag = tag; return this; } @Nullable public View getCustomView() { return this.customView; } @NonNull public TabLayout.Tab setCustomView(@Nullable View view) { this.customView = view; this.updateView(); return this; } @NonNull public TabLayout.Tab setCustomView(@LayoutRes int resId) { LayoutInflater inflater = LayoutInflater.from(this.view.getContext()); return this.setCustomView(inflater.inflate(resId, this.view, false)); } } }
三、修改方案
获取 TabLayout.Tab 中的 customView , view , 二者任意一个都可以 , customView 私有变量有公共的 getter 方法 , view 直接就是公共变量 , 可以直接访问 ;
private View customView; public TabLayout.TabView view; @Nullable public View getCustomView() { return this.customView; }
将代码改为 :
TabLayout.Tab tab = tabLayout.getTabAt(i); Field mViewField = null; try { mViewField = TabLayout.Tab.class.getDeclaredField("mView"); } catch (NoSuchFieldException e) { e.printStackTrace(); } mViewField.setAccessible(true); try { View mView = (View) mViewField.get(tab); } catch (IllegalAccessException e) { e.printStackTrace(); }