Activity中使用PagerAdapter实现切换代码
主活动
public class ViewPagerManager extends AppCompatActivity {
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_manager);
viewPager = findViewById(R.id.viewpager);
initView();
}
private void initView() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add("第"+i+"个View");
}
viewPager.setAdapter(new Adapter(this,list));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
activity_view_pager_manager布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPagerManager">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
adapter:
public class Adapter extends PagerAdapter {
private Context mContext;
private List<String> mData;
public Adapter(Context context ,List<String> list) {
mContext = context;
mData = list;
}
@Override
public int getCount() {
return mData.size(http://www.amjmh.com/v/BIBRGZ_558768/);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = View.inflate(mContext, R.layout.activity_view_pager_item,null);
TextView tv = view.findViewById(R.id.textaa);
tv.setText(mData.get(position));
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
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
activity_view_pager_item布局:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/textaa"
android:gravity="center"
android:text="sadsadsa"
>
</TextView>