TabLayout.Tab(自定義)點擊事件


TabLayout是官方design包中的一個布局控件,這里不介紹它的基本使用,只是解決Tab(自定義)點擊事件。


 1 //獲取Tab的數量
 2 
 3 Int tabCount = tabLayout.getTabCount();  
 4 
 5 for(int i = 0 ; i < tabCount; i++){
 6 
 7 TabLayout.Tab tab = tabLayout.getTabAt(i);
 8 
 9 if(tab == null){
10 
11 continue;
12 
13 }
14 
15 //這里使用到反射,拿到Tab對象后獲取Class
16 
17 Class c = tab.getClass();
18 
19 try{
20 
21  //c.getDeclaredField 獲取私有屬性。
22 
23 //“mView”是Tab的私有屬性名稱,類型是 TabView ,TabLayout私有內部類。
24 
25 Field field = c.getDeclaredField("mView");
26 
27 if(field ==null) {
28 
29 continue;
30 
31 }
32 
33 field.setAccessible(true);
34 
35 final View view = (View) field.get(tab);
36 
37 if(view ==null) {
38 
39 continue;
40 
41 }
42 
43 view.setTag(i);
44 
45 view.setOnClickListener(newView.OnClickListener() {
46 
47 @Override
48 
49 public void onClick(View v) {
50 
51 //這里就可以根據業務需求處理事件了。
52 
53 int position = (int)view.getTag(); 
54 
55 mViewPager.setCurrentItem(position, false);
56 
57 }
58 
59 });
60 
61 }catch(NoSuchFieldException e) {
62 
63 e.printStackTrace();
64 
65 }catch(IllegalAccessException e) {
66 
67 e.printStackTrace();
68 
69 }
70 
71 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM