当前位置:
首页 >
【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28.0.0 后源码发生变更 )
发布时间:2025/6/17
61
豆豆
生活随笔
收集整理的这篇文章主要介绍了
【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28.0.0 后源码发生变更 )
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
文章目录
- 一、报错信息
- 二、错误分析
- 三、修改方案
一、报错信息
之前开发 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();} 《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读总结
以上是生活随笔为你收集整理的【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28.0.0 后源码发生变更 )的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【计算机网络】HTTP 与 HTTPS
- 下一篇: 【OkHttp】OkHttp 简介 (