多可左右滑动的分页容器模板

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
import android.support.v7.app.AppCompatActivity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter; // 适配器
private ViewPager mViewPager; // 容器

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 通过 FragmentManager 创建适配器
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

// 设置 ViewPager 容器
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}


/* fragment 类 */
public static class PlaceholderFragment extends Fragment {
// 定义一个储存参数的key的常量
private static final String ARG_SECTION_NUMBER = "section_number";

public PlaceholderFragment() {
}

// 创建一个 fragment,好像是工厂模式?(静态)
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}

// 返回一个 inflate 的 view,并且读取参数并设置
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}

/* 适配器 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}

// 只在第一次的时候才需要 getItem,创建一个fragment
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}

@Override
public int getCount() {
return 3;
}
}
}