【错误记录】TabLayout 升级支持库版本后报错 ( support:design 支持库升级到 28.0.0 后源码发生变更 )
生活随笔
收集整理的這篇文章主要介紹了
【错误记录】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 简介 (