2019-09-15 | UNLOCK

安卓开发之ViewPager

AS实现ViewPager滑动切换布局效果(类似于swiper)
步骤:
1、新建一个MyNewAdapter类
2、更改mainActivity布局xml,添加新控件ViewPager
3、修改mainActivity.java,将其绑定到指定的布局

1、新建一个MyNewAdapter类

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
package cn.edu.szpt.viewpager0244;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;

public class MyNewAdapter extends PagerAdapter{

List<View> views;
//构造方法
public MyNewAdapter(List<View> views){
this.views = views;
}

//重写
@Override
public int getCount(){
return views.size();
}
@Override
public boolean isViewFromObject(View arg0,Object arg1){
return arg0 == arg1;
}
@Override
public void destroyItem(ViewGroup container,int position, Object object){
((ViewPager)container).removeView(views.get(position));
}
@Override
public Object instantiateItem(ViewGroup container,int position){
((ViewPager)container).addView(views.get((position)));
return views.get(position);
}
}

2、更改mainActivity布局xml,添加新控件ViewPager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>

</LinearLayout>

3、修改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
package cn.edu.szpt.viewpager0244;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
MyNewAdapter adapter;
List<View> views;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.viewpager);
views = new ArrayList<View>();
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());

View view1 = inflater.inflate(R.layout.tab1, null);
View view2 = inflater.inflate(R.layout.tab2, null);
View view3 = inflater.inflate(R.layout.tab3, null);
views.add(view1);
views.add(view2);
views.add(view3);

adapter = new MyNewAdapter(views);
viewPager.setAdapter(adapter);
}
}

最后注意一下,需要创建3个布局,可以通过创建类+布局或者直接创建布局(tab1.xml、tab2.xml、tab3.xml)布局内容自定。