300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28

【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28

时间:2024-04-12 08:47:34

相关推荐

【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28

文章目录

一、报错信息二、错误分析三、修改方案

一、报错信息

之前开发 TabLayout 使用的是com.android.support:design:25.3.1支持库 ,

implementation 'com.android.support:design:25.3.1'

现在升级到 28.0.028.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() {}@Nullablepublic Object getTag() {return this.tag;}@NonNullpublic TabLayout.Tab setTag(@Nullable Object tag) {this.tag = tag;return this;}@Nullablepublic View getCustomView() {return this.customView;}@NonNullpublic TabLayout.Tab setCustomView(@Nullable View view) {this.customView = view;this.updateView();return this;}@NonNullpublic 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;@Nullablepublic 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();}

【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28.0.0 后源码发生变更 )

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。