Proper implementation of ViewPager2 in Android(在 Android 中正确实现 ViewPager2)
问题描述
我了解了 ViewPager2 并尝试了实现它,但没有找到任何合适的例子.
谁能告诉我如何使用它.
我正在寻找正确的用法,而不是示例.
UPDATE 7
检查:从 ViewPager 迁移到 ViewPager2
检查:使用 ViewPager2 创建带有标签的滑动视图
更新 6
如果您想使用 View Pager2 实现轮播,请查看我的回答
更新 5
<块引用>如何在 ViewPager2 中使用 TabLayout
示例代码
在依赖项
实现 'com.google.android.material:material:1.1.0-alpha08'实施 'androidx.viewpager2:viewpager2:1.0.0-beta02'
示例代码
<块引用>XML 布局
<?xml version="1.0" encoding="utf-8"?>
<块引用>
活动
导入androidx.appcompat.app.AppCompatActivity导入 android.os.Bundle导入 kotlinx.android.synthetic.main.activity_main.*导入 com.google.android.material.tabs.TabLayoutMediator导入 com.google.android.material.tabs.TabLayout类 MainActivity : AppCompatActivity() {覆盖 fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//setSupportActionBar(工具栏)viewpager.adapter = AppViewPagerAdapter(supportFragmentManager,生命周期)TabLayoutMediator(标签,viewpager,对象:TabLayoutMediator.OnConfigureTabCallback {覆盖乐趣 onConfigureTab(tab: TabLayout.Tab, position: Int) {//在此处设置每个选项卡的样式tab.text = "标签$位置"}}).附()}}
<块引用>
输出
带有 ViewPager2 的 TabLayout
来自文档
ViewPager2
新功能
- 从右到左 (RTL) 布局支持
- 垂直方向支持
- notifyDataSetChanged 功能齐全
API 更改
FragmentStateAdapter
替换FragmentStatePagerAdapter
RecyclerView.Adapter
替换PagerAdapter
registerOnPageChangeCallback
替换addPageChangeListener
示例代码
<块引用>为ViewPager2
dependencies
实现 'androidx.viewpager2:viewpager2:1.0.0-alpha01'
<块引用>
布局
<?xml version="1.0" encoding="utf-8"?><线性布局 xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"机器人:方向=垂直"工具:context=".MainActivity">
<块引用>
活动
导入android.os.Bundle;导入androidx.appcompat.app.AppCompatActivity;导入androidx.viewpager2.widget.ViewPager2;导入 java.util.ArrayList;公共类 MyActivity 扩展 AppCompatActivity {ViewPager2 我的ViewPager2;我的适配器我的适配器;私有数组列表<字符串>数组列表 = 新数组列表<>();@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_my);myViewPager2 = findViewById(R.id.view_pager);arrayList.add("项目 1");arrayList.add("项目 2");arrayList.add("项目 3");arrayList.add("项目 4");arrayList.add("项目 5");MyAdapter = new MyAdapter(this, arrayList);myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);myViewPager2.setAdapter(MyAdapter);}}
<块引用>
我的适配器
导入android.content.Context;导入 android.view.LayoutInflater;导入android.view.View;导入android.view.ViewGroup;导入 android.widget.TextView;导入androidx.annotation.NonNull;导入androidx.recyclerview.widget.RecyclerView;导入 java.util.ArrayList;公共类 MyAdapter 扩展 RecyclerView.Adapter{私有上下文上下文;私有数组列表<字符串>数组列表 = 新数组列表<>();公共 MyAdapter(上下文上下文,ArrayList<String>arrayList){this.context = 上下文;this.arrayList = 数组列表;}@NonNull@覆盖public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {查看视图 = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);返回新的 MyViewHolder(视图);}@覆盖public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {holder.tvName.setText(arrayList.get(position));}@覆盖公共 int getItemCount() {返回 arrayList.size();}公共类 MyViewHolder 扩展 RecyclerView.ViewHolder {TextView 电视名称;public MyViewHolder(@NonNull View itemView) {超级(项目视图);tvName = itemView.findViewById(R.id.tvName);}}}
新功能
<块引用>现在我们需要使用 ViewPager2.OnPageChangeCallback()
来获取 ViewPager2
示例代码
myViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {@覆盖public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {super.onPageScrolled(位置, positionOffset, positionOffsetPixels);}@覆盖公共无效 onPageSelected(int position) {super.onPageSelected(位置);Log.e("Selected_Page", String.valueOf(position));}@覆盖公共无效 onPageScrollStateChanged(int state) {super.onPageScrollStateChanged(状态);}});
<块引用>
我们可以使用 myViewPager2.setOrientation()
示例代码
对于 水平方向
使用
myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
对于垂直方向
使用
myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
<块引用>
我们可以像在 RecyclerView.Adapter
notifyDataSetChanged
添加新项目的示例代码
btnAdd.setOnClickListener(new View.OnClickListener() {@覆盖public void onClick(查看视图){arrayList.add("新项目添加");MyAdapter.notifyDataSetChanged();}});
删除新项目的示例代码
btnRemove.setOnClickListener(new View.OnClickListener() {@覆盖public void onClick(查看视图){arrayList.remove(3);MyAdapter.notifyItemRemoved(3);}});
更新
如果你想用 Fragment
和 ViewPager2
试试这个<块引用>首先创建一个扩展FragmentStateAdapter
ViewPagerFragmentAdapter
类import java.util.ArrayList;导入androidx.annotation.NonNull;导入androidx.fragment.app.Fragment;导入androidx.fragment.app.FragmentManager;导入 androidx.viewpager2.adapter.FragmentStateAdapter;公共类 ViewPagerFragmentAdapter 扩展 FragmentStateAdapter {私有数组列表<片段>数组列表 = 新数组列表<>();公共 ViewPagerFragmentAdapter(@NonNull FragmentManager fragmentManager) {超级(片段管理器);}@NonNull@覆盖公共片段getItem(int位置){返回arrayList.get(位置);}公共无效addFragment(片段片段){arrayList.add(片段);}@覆盖公共 int getItemCount() {返回 arrayList.size();}}
<块引用>
现在在你的活动中像这样使用
import androidx.annotation.Nullable;导入androidx.appcompat.app.AppCompatActivity;导入androidx.viewpager2.widget.ViewPager2;进口neel.com.bottomappbar.R;公共类 MainActivity 扩展 AppCompatActivity {ViewPager2 我的ViewPager2;ViewPagerFragmentAdapter myAdapter;@覆盖protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myViewPager2 = findViewById(R.id.view_pager);myAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager());//在 ViewPagerFragmentAdapter 类中添加片段myAdapter.addFragment(new FragmentOne());myAdapter.addFragment(new Fragmenttwo());myAdapter.addFragment(new FragmentThree());//在 ViewPager2 中设置方向myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);myViewPager2.setAdapter(myAdapter);}}
欲了解更多信息,请查看此
- ViewPager2
- ViewPager2 底层
- 实践 ViewPager2
更新 2
<块引用>版本 1.0.0-alpha02
新功能
- 能够禁用用户输入(
setUserInputEnabled
、isUserInputEnabled
)
API 更改
ViewPager2
最终类
错误修复
FragmentStateAdapter
稳定性修复
在 viewpager2 中禁用滑动的示例代码
myViewPager2.setUserInputEnabled(false);//在 viewpager2 中禁用滑动的示例代码myViewPager2.setUserInputEnabled(true);//在 viewpager2 中启用滑动的示例代码
更新 3
<块引用>版本 1.0.0-alpha03
新功能
- 能够以编程方式滚动 ViewPager2:fakeDragBy(offsetPx).
API 更改
FragmentStateAdapter
现在需要一个Lifecycle
对象.添加了两个实用程序构造函数以从主机FragmentActivity
或主机 Fragment 获取它
示例代码
<块引用>ViewPagerFragmentAdapter
import java.util.ArrayList;导入androidx.annotation.NonNull;导入androidx.fragment.app.Fragment;导入androidx.fragment.app.FragmentManager;导入androidx.lifecycle.Lifecycle;导入 androidx.viewpager2.adapter.FragmentStateAdapter;公共类 ViewPagerFragmentAdapter 扩展 FragmentStateAdapter {私有数组列表<片段>数组列表 = 新数组列表<>();公共 ViewPagerFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle 生命周期) {超级(片段管理器,生命周期);}@NonNull@覆盖公共片段getItem(int位置){返回arrayList.get(位置);}公共无效addFragment(片段片段){arrayList.add(片段);}@覆盖公共 int getItemCount() {返回 arrayList.size();}}
<块引用>
MainActivity 代码
导入android.os.Bundle;导入androidx.annotation.Nullable;导入androidx.appcompat.app.AppCompatActivity;导入androidx.viewpager2.widget.ViewPager2;进口neel.com.bottomappbar.R;公共类 MainActivity 扩展 AppCompatActivity {ViewPager2 我的ViewPager2;ViewPagerFragmentAdapter myAdapter;@覆盖protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myViewPager2=findViewById(R.id.view_pager);myAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager(), getLifecycle());//在 ViewPagerFragmentAdapter 类中添加片段myAdapter.addFragment(new FragmentOne());myAdapter.addFragment(new Fragmenttwo());myAdapter.addFragment(new FragmentThree());myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);myViewPager2.setAdapter(myAdapter);}}
更新 4
<块引用>版本 1.0.0-alpha05代码>
新功能
ItemDecorator
引入了与RecyclerView
一致的行为.MarginPageTransformer
引入以提供在页面之间创建空间的能力(页面插入之外).CompositePageTransformer
引入以提供组合多个PageTransformer
的能力
API 更改
FragmentStateAdapter#getItem
方法重命名为FragmentStateAdapter#createFragment
- 以前的方法名称已被证明是过去的错误来源.OFFSCREEN_PAGE_LIMIT_DEFAULT
值从 0 更改为 -1.如果使用了OFFSCREEN_PAGE_LIMIT_DEFAULTconstant
,则无需更改客户端代码.
示例代码
<块引用>活动代码
import androidx.annotation.NonNull;导入androidx.annotation.Nullable;导入androidx.appcompat.app.AppCompatActivity;导入androidx.fragment.app.Fragment;导入androidx.recyclerview.widget.RecyclerView;导入androidx.viewpager2.widget.MarginPageTransformer;导入androidx.viewpager2.widget.ViewPager2;进口neel.com.bottomappbar.R;公共类 MainActivity 扩展 AppCompatActivity {ViewPager2 我的ViewPager2;ViewPagerFragmentAdapter myAdapter;私有数组列表<片段>数组列表 = 新数组列表<>();@覆盖protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myViewPager2 = findViewById(R.id.myViewPager2);//在 ViewPagerFragmentAdapter 类中添加片段arrayList.add(new FragmentOne());arrayList.add(new Fragmenttwo());arrayList.add(new FragmentThree());myAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager(), getLifecycle());//在 ViewPager2 中设置方向myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);myViewPager2.setAdapter(myAdapter);myViewPager2.setPageTransformer(new MarginPageTransformer(1500));}}
<块引用>
ViewPagerFragmentAdapter
import java.util.ArrayList;导入androidx.annotation.NonNull;导入androidx.fragment.app.Fragment;导入androidx.fragment.app.FragmentManager;导入androidx.lifecycle.Lifecycle;导入 androidx.viewpager2.adapter.FragmentStateAdapter;公共类 ViewPagerFragmentAdapter 扩展 FragmentStateAdapter {私有数组列表<片段>数组列表 = 新数组列表<>();公共 ViewPagerFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle 生命周期) {超级(片段管理器,生命周期);}@NonNull@覆盖公共片段 createFragment(int position) {开关(位置){案例0:返回新的 FragmentOne();情况1:返回新的 Fragmenttwo();案例2:返回新的 FragmentThree();}返回空值;}@覆盖公共 int getItemCount() {返回 3;}}
I came to know about ViewPager2 and tried to implement it, but didn't find any proper example.
Can anyone tell me how can I use it.
I am looking for proper usage, not an example.
UPDATE 7
Check : Migrate from ViewPager to ViewPager2
Check : Create swipe views with tabs using ViewPager2
UPDATE 6
Check out my answer if you want to implement Carousel using View Pager2
UPDATE 5
How to use TabLayout with ViewPager2
SAMPLE CODE
Use below dependencies
implementation 'com.google.android.material:material:1.1.0-alpha08'
implementation 'androidx.viewpager2:viewpager2:1.0.0-beta02'
SAMPLE CODE
XMl layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewpager"
app:layout_anchor="@id/tabs"
app:layout_anchorGravity="bottom"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import com.google.android.material.tabs.TabLayoutMediator
import com.google.android.material.tabs.TabLayout
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// setSupportActionBar(toolbar)
viewpager.adapter = AppViewPagerAdapter(supportFragmentManager, lifecycle)
TabLayoutMediator(tabs, viewpager, object : TabLayoutMediator.OnConfigureTabCallback {
override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
// Styling each tab here
tab.text = "Tab $position"
}
}).attach()
}
}
OUTPUT
TabLayout with ViewPager2
From Docs
ViewPager2
New features
- Right-to-left (RTL) layout support
- Vertical orientation support
- notifyDataSetChanged fully functional
API changes
FragmentStateAdapter
replacesFragmentStatePagerAdapter
RecyclerView.Adapter
replacesPagerAdapter
registerOnPageChangeCallback
replacesaddPageChangeListener
SAMPLE CODE
add the latest
dependencies
forViewPager2
implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha01'
layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
activity
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import java.util.ArrayList;
public class MyActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
MyAdapter MyAdapter;
private ArrayList<String> arrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myViewPager2 = findViewById(R.id.view_pager);
arrayList.add("Item 1");
arrayList.add("Item 2");
arrayList.add("Item 3");
arrayList.add("Item 4");
arrayList.add("Item 5");
MyAdapter = new MyAdapter(this, arrayList);
myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
myViewPager2.setAdapter(MyAdapter);
}
}
MyAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> arrayList = new ArrayList<>();
public MyAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.tvName.setText(arrayList.get(position));
}
@Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName);
}
}
}
New features
now we need to use
ViewPager2.OnPageChangeCallback()
to get Swipe event ofViewPager2
SAMPLE CODE
myViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Log.e("Selected_Page", String.valueOf(position));
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
we can set Orientation using
myViewPager2.setOrientation()
SAMPLE CODE
For HORIZONTAL Orientation
use
myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
For VERTICAL Orientation
use
myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
We can use
notifyDataSetChanged
same as we are using inRecyclerView.Adapter
SAMPLE CODE to add new item
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
arrayList.add("New ITEM ADDED");
MyAdapter.notifyDataSetChanged();
}
});
SAMPLE CODE to remove new item
btnRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
arrayList.remove(3);
MyAdapter.notifyItemRemoved(3);
}
});
UPDATE
Try this if you want to use Fragment
with ViewPager2
First create a
ViewPagerFragmentAdapter
class which extendsFragmentStateAdapter
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
public class ViewPagerFragmentAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public ViewPagerFragmentAdapter(@NonNull FragmentManager fragmentManager) {
super(fragmentManager);
}
@NonNull
@Override
public Fragment getItem(int position) {
return arrayList.get(position);
}
public void addFragment(Fragment fragment) {
arrayList.add(fragment);
}
@Override
public int getItemCount() {
return arrayList.size();
}
}
Now use like this in your activity
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import neel.com.bottomappbar.R;
public class MainActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
ViewPagerFragmentAdapter myAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myViewPager2 = findViewById(R.id.view_pager);
myAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager());
// add Fragments in your ViewPagerFragmentAdapter class
myAdapter.addFragment(new FragmentOne());
myAdapter.addFragment(new Fragmenttwo());
myAdapter.addFragment(new FragmentThree());
// set Orientation in your ViewPager2
myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
myViewPager2.setAdapter(myAdapter);
}
}
for more information check this
- ViewPager2
- ViewPager2 under the Hood
- Hands on With ViewPager2
UPDATE 2
Version 1.0.0-alpha02
New features
- Ability to disable user input (
setUserInputEnabled
,isUserInputEnabled
)
API changes
ViewPager2
class final
Bug fixes
FragmentStateAdapter
stability fixes
SAMPLE CODE to disable swiping in viewpager2
myViewPager2.setUserInputEnabled(false);// SAMPLE CODE to disable swiping in viewpager2
myViewPager2.setUserInputEnabled(true);//SAMPLE CODE to enable swiping in viewpager2
UPDATE 3
Version 1.0.0-alpha03
New features
- Ability to programmatically scroll ViewPager2: fakeDragBy(offsetPx).
API changes
FragmentStateAdapter
now requires aLifecycle
object. Two utility constructors added to obtain it from the hostFragmentActivity
or the host Fragment
SAMPLE CODE
ViewPagerFragmentAdapter
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
public class ViewPagerFragmentAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public ViewPagerFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
@NonNull
@Override
public Fragment getItem(int position) {
return arrayList.get(position);
}
public void addFragment(Fragment fragment) {
arrayList.add(fragment);
}
@Override
public int getItemCount() {
return arrayList.size();
}
}
MainActivity code
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import neel.com.bottomappbar.R;
public class MainActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
ViewPagerFragmentAdapter myAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myViewPager2=findViewById(R.id.view_pager);
myAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager(), getLifecycle());
// add Fragments in your ViewPagerFragmentAdapter class
myAdapter.addFragment(new FragmentOne());
myAdapter.addFragment(new Fragmenttwo());
myAdapter.addFragment(new FragmentThree());
myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
myViewPager2.setAdapter(myAdapter);
}
}
UPDATE 4
Version 1.0.0-alpha05
New features
ItemDecorator
introduced with a behaviour consistent withRecyclerView
.MarginPageTransformer
introduced to provide an ability to create space between pages (outside of page inset).CompositePageTransformer
introduced to provide an ability to combine multiplePageTransformers
API changes
FragmentStateAdapter#getItem
method renamed toFragmentStateAdapter#createFragment
- previous method name has proven to be a source of bugs in the past.OFFSCREEN_PAGE_LIMIT_DEFAULT
value changed from 0 to -1. No need for a client code change if theOFFSCREEN_PAGE_LIMIT_DEFAULTconstant
used.
SAMPLE CODE
Activity code
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.MarginPageTransformer;
import androidx.viewpager2.widget.ViewPager2;
import neel.com.bottomappbar.R;
public class MainActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
ViewPagerFragmentAdapter myAdapter;
private ArrayList<Fragment> arrayList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myViewPager2 = findViewById(R.id.myViewPager2);
// add Fragments in your ViewPagerFragmentAdapter class
arrayList.add(new FragmentOne());
arrayList.add(new Fragmenttwo());
arrayList.add(new FragmentThree());
myAdapter = new ViewPagerFragmentAdapter(getSupportFragmentManager(), getLifecycle());
// set Orientation in your ViewPager2
myViewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
myViewPager2.setAdapter(myAdapter);
myViewPager2.setPageTransformer(new MarginPageTransformer(1500));
}
}
ViewPagerFragmentAdapter
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
public class ViewPagerFragmentAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public ViewPagerFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new Fragmenttwo();
case 2:
return new FragmentThree();
}
return null;
}
@Override
public int getItemCount() {
return 3;
}
}
这篇关于在 Android 中正确实现 ViewPager2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Android 中正确实现 ViewPager2
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- UITextView 内容插图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- URL编码Swift iOS 2022-01-01