给我提供一份Fragment+viewpager2的java demo源码
时间: 2024-01-15 09:03:18 浏览: 136
好的,以下是一个简单的Fragment viewpager2的java demo源码:
```java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import java.util.ArrayList;
import java.util.List;
public class MyFragment extends Fragment {
private ViewPager2 viewPager;
private MyAdapter adapter;
private List<String> data;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
// 初始化ViewPager2和数据
viewPager = view.findViewById(R.id.viewPager2);
data = new ArrayList<>();
data.add("Page 1");
data.add("Page 2");
data.add("Page 3");
// 设置ViewPager2的adapter
adapter = new MyAdapter(data);
viewPager.setAdapter(adapter);
return view;
}
}
```
注意:本段代码仅供参考,需要根据实际情况进行修改和优化。
阅读全文