生成一个有viewpager的Android代码
时间: 2024-05-07 19:22:41 浏览: 68
android实现viewpager的例子
以下是一个简单的包含 ViewPager 的 Android 代码:
```xml
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
```java
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
List<String> data = new ArrayList<>();
data.add("Page 1");
data.add("Page 2");
data.add("Page 3");
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), data);
viewPager.setAdapter(adapter);
}
private static class MyPagerAdapter extends FragmentPagerAdapter {
private List<String> data;
public MyPagerAdapter(FragmentManager fm, List<String> data) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.data = data;
}
@NonNull
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(data.get(position));
}
@Override
public int getCount() {
return data.size();
}
}
public static class PageFragment extends Fragment {
private static final String ARG_PAGE_TITLE = "pageTitle";
public static PageFragment newInstance(String pageTitle) {
Bundle args = new Bundle();
args.putString(ARG_PAGE_TITLE, pageTitle);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
TextView pageTitleTextView = view.findViewById(R.id.pageTitleTextView);
String pageTitle = getArguments().getString(ARG_PAGE_TITLE);
pageTitleTextView.setText(pageTitle);
return view;
}
}
}
```
这个代码定义了一个包含 ViewPager 的布局文件,以及一个自定义 PagerAdapter 和 Fragment 类。在 onCreate 方法中,ViewPager 被实例化并设置了 PagerAdapter。PagerAdapter 负责提供 Fragment 及其数据,而 Fragment 负责显示页面内容。
阅读全文