27. Fragment + ViewPager
27.1 fragment与viewPager的联合应用
ViewPager + Fragment形成翻页效果
→ 减少用户的操作。
27.2 ViewPager2基本应用
新的空白工程
布局文件
<?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">
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewpager"
android:background="#ff00ff"
/>
</LinearLayout>
定义适配器Adapter类
package com.dingjiaxiong.myviewpagerandfragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ViewPageAdapter extends RecyclerView.Adapter<ViewPageAdapter.ViewPagerViewHolder> {
private List<String> titles = new ArrayList<>();
public ViewPageAdapter(){
titles.add("hello");
titles.add("w");
titles.add("o");
titles.add("r");
titles.add("l");
titles.add("d");
titles.add("Android");
titles.add("Java");
titles.add("How");
titles.add("?");
}
@NonNull
@Override
public ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager,parent,false));
}
//定义view适配
@Override
public void onBindViewHolder(@NonNull ViewPagerViewHolder holder, int position) {
holder.mTv.setText(titles.get(position));
}
@Override
public int getItemCount() {
return 10;
}
class ViewPagerViewHolder extends RecyclerView.ViewHolder{
TextView mTv;
RelativeLayout mContainer;
public ViewPagerViewHolder(@NonNull View itemView) {
super(itemView);
mContainer = itemView.findViewById(R.id.container);
mTv = itemView.findViewById(R.id.tvTitle);
}
}
}
适配布局
item_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvTitle"
android:layout_centerInParent="true"
android:textColor="#ff4532"
android:textSize="32sp"
android:text="hello"
/>
</RelativeLayout>
MainActivity.java
package com.dingjiaxiong.myviewpagerandfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager2 viewPager = findViewById(R.id.viewpager);
ViewPageAdapter viewPageAdapter = new ViewPageAdapter();
viewPager.setAdapter(viewPageAdapter);
}
}
运行
27.3 页面的切换
更改背景颜色即可
private List<Integer> colors = new ArrayList<>();
public ViewPageAdapter(){
colors.add(R.color.white);
colors.add(R.color.black);
colors.add(R.color.purple_200);
colors.add(R.color.red);
colors.add(R.color.purple_500);
colors.add(R.color.purple_700);
colors.add(R.color.teal_200);
colors.add(R.color.teal_700);
colors.add(R.color.red);
colors.add(R.color.teal_200);
运行
27.4 ViewPager的使用流程
- 定义ViewPager
- 为ViewPager构建Adapter
27.5 ViewPager + Fragment形成翻页效果
仿微信
创建空项目
MainActivity.java
package com.dingjiaxiong.wechatpage;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ViewPager2 viewPager;
private LinearLayout llchat , llcontacts , llfind , llprofiles;
private ImageView ivChat , ivContact , ivFind ,ivMe , ivCurrent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPager();
initTabView();
}
private void initTabView() {
llchat = findViewById(R.id.id_tab_weixin);
llchat.setOnClickListener(this);
llcontacts = findViewById(R.id.id_tab_cantact);
llcontacts.setOnClickListener(this);
llfind = findViewById(R.id.id_tab_search);
llfind.setOnClickListener(this);
llprofiles = findViewById(R.id.id_tab_me);
llprofiles.setOnClickListener(this);
ivChat = findViewById(R.id.tab_iv_weixin);
ivContact = findViewById(R.id.tab_iv_contact);
ivFind = findViewById(R.id.tab_iv_search);
ivMe = findViewById(R.id.tab_iv_me);
ivChat.setSelected(true);
ivCurrent = ivChat;
}
private void initPager() {
viewPager = findViewById(R.id.id_viewpager);
ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(BlankFragment.newInstance("微信聊天"));
fragments.add(BlankFragment.newInstance("通讯录"));
fragments.add(BlankFragment.newInstance("发现"));
fragments.add(BlankFragment.newInstance("我"));
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
viewPager.setAdapter(pagerAdapter);
viewPager.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);
changeTab(position);
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
private void changeTab(int position) {
ivCurrent.setSelected(false);
switch (position){
case R.id.id_tab_weixin:
viewPager.setCurrentItem(0);
case 0:
ivChat.setSelected(true);
ivCurrent = ivChat;
break;
case R.id.id_tab_cantact:
viewPager.setCurrentItem(1);
case 1:
ivContact.setSelected(true);
ivCurrent = ivContact;
break;
case R.id.id_tab_search:
viewPager.setCurrentItem(2);
case 2:
ivFind.setSelected(true);
ivCurrent = ivFind;
break;
case R.id.id_tab_me:
viewPager.setCurrentItem(3);
case 3:
ivMe.setSelected(true);
ivCurrent = ivMe;
break;
}
}
@Override
public void onClick(View view) {
changeTab(view.getId());
}
}
BlankFragment.java
package com.dingjiaxiong.wechatpage;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
private static final String ARG_TEXT = "param1";
// TODO: Rename and change types of parameters
private String mTextString;
View rootview;
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTextString = getArguments().getString(ARG_TEXT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(rootview == null){
rootview = inflater.inflate(R.layout.fragment_blank, container, false);
}
initView();
return rootview;
}
private void initView() {
TextView textView = rootview.findViewById(R.id.text);
textView.setText(mTextString);
}
}
MyFragmentPagerAdapter.java
package com.dingjiaxiong.wechatpage;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
import java.util.List;
public class MyFragmentPagerAdapter extends FragmentStateAdapter {
List<Fragment> fragmentList = new ArrayList<>();
public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,List<Fragment> fragments) {
super(fragmentManager, lifecycle);
fragmentList = fragments;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}
activity_main.xml
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/id_viewpager"
/>
<include layout="@layout/bottom_layout"></include>
</LinearLayout>
bottom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dp"
android:orientation="horizontal"
android:background="@color/gray"
>
<LinearLayout
android:gravity="center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:orientation="vertical"
android:id="@+id/id_tab_weixin"
>
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
android:id="@+id/tab_iv_weixin"
android:background="@drawable/tab_weixin"
/>
<TextView
android:layout_width="32dp"
android:layout_height="wrap_content"
android:id="@+id/text_weixin"
android:gravity="center"
android:text="微信"
/>
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:orientation="vertical"
android:id="@+id/id_tab_cantact"
>
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
android:id="@+id/tab_iv_contact"
android:background="@drawable/tab_cantact"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_cantact"
android:gravity="center"
android:text="通讯录"
/>
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:orientation="vertical"
android:id="@+id/id_tab_search"
>
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
android:id="@+id/tab_iv_search"
android:background="@drawable/tab_search"
/>
<TextView
android:layout_width="32dp"
android:layout_height="wrap_content"
android:id="@+id/text_search"
android:gravity="center"
android:text="发现"
/>
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:orientation="vertical"
android:id="@+id/id_tab_me"
>
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
android:id="@+id/tab_iv_me"
android:background="@drawable/tab_mine"
/>
<TextView
android:layout_width="32dp"
android:layout_height="wrap_content"
android:id="@+id/text_me"
android:gravity="center"
android:text="我"
/>
</LinearLayout>
</LinearLayout>
fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/text"
android:gravity="center"
android:textSize="36sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
运行效果