-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainActivity.java
108 lines (87 loc) · 3.14 KB
/
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.example.again;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private int[] TabRes = new int[]{R.drawable.shouye, R.drawable.kefu, R.drawable.tianjia};
private String[] titles = new String[]{"首页", "客服", "添加"};
private ViewPager viewPager;
private TabLayout tabLayout;
private TabLayout.Tab tabAtOne;
private TabLayout.Tab tabAttwo;
private TabLayout.Tab tabAtthree;
private TabLayout.Tab tabAtfour;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
initView();
initDate();
}
private void initView() {
viewPager = (ViewPager) findViewById(R.id.viewpager_content_view);
tabLayout = (TabLayout) findViewById(R.id.tab_layout_view);
//使用适配器将ViewPager与Fragment绑定在一起
viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
//将TabLayout与ViewPager绑定
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < titles.length; i++) {
tabLayout.getTabAt(i).setIcon(TabRes[i]);
}
}
private void initDate(){
}
public void initListener(){
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
for (int i = 0; i < titles.length; i++) {
if(tab == tabLayout.getTabAt(i)){
tabLayout.getTabAt(i).setIcon(TabRes[i]);
viewPager.setCurrentItem(i);
}
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
for (int i = 0; i < titles.length; i++) {
tabLayout.getTabAt(i).setIcon(TabRes[i]);
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
public MyFragmentPagerAdapter(FragmentManager fm){
super(fm);
}
@NonNull
@Override
public Fragment getItem(int position) {
if(position == 1){
return new SecondFragment();
}else if(position == 2){
return new ThirdFragment();
}
return new FirstFragment();
}
@Override
public int getCount() {
return titles.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}