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 }