Fragment

Fragment的产生

什么是Fragment

Fragment的使用方法

MainActivity.java

package a.b.c.fragmentbase;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

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

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

<fragment
android:name="a.b.c.fragmentbase.BlankFragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@id/fragment1"/>
</LinearLayout>

BlankFragment1.java

package a.b.c.fragmentbase;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class BlankFragment1 extends Fragment{
private View root;
private TextView textView;
private Button button;

@Override
public void onCreate(Bundle saveInstanceState){
super.onCreate(savedInstanceState);
}
@Override
public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
if(root == null){
root = inflater.inflate(R.layout.fragment_blank1, container, false);
}
textView = root.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
textView.setText("Yes, I am, and you?");
}
});
return root;
}
}

fragment_blank1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="@string/hello_blank_fragment"
android:id="@+id/textview"/>

<Button
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/btn"
android:text="How are you?"/>
</LinearLayout>

在activity中简单的添加两个fragment

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

<fragment
android:name="a.b.c.fragmentbase.BlankFragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/fragment1"/>

<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="a.b.c.fragmentbase.BlankFragment2"
android:layout_weight="1"
android:id="@+id/fragment2"/>

</LinearLayout>

Fragment的产生

动态添加Fragment

JDK17以上版本无法使用switch的解决方法:

MainActivity.java

package a.b.c.fragmentmangers;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn;
private Button btn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn); // 使用正确的 ID
btn.setOnClickListener(this);
btn2 = findViewById(R.id.btn_2); // 处理其他按钮
btn2.setOnClickListener(this);
}

@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn:
replaceFragment(new BlankFragment1());
break;

case R.id.btn_2:
replaceFragment(new ItemFragment());
break;
}
}

private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.framelayout,fragment);
transaction.addToBackStack(null);//添加到同一个栈中,这样用户可以按返回键时回到之前的状态。
/*replace(int containerViewId, Fragment fragment) 是 FragmentTransaction 类中的一个方法,用于将一个 Fragment 替换到指定的容器中。

containerViewId: 这是一个 int 类型的参数,表示容器的资源 ID。这个容器通常是一个 FrameLayout 或者其他可以承载 Fragment 的视图组件。你在布局文件中定义这个容器时会为它分配一个 ID(在这个例子中是 R.id.framelayout)。

fragment: 这是你希望替换到容器中的新的 Fragment 实例。这个 Fragment 对象是你要显示的新内容或界面。*/
transaction.commit();
}
}

BlankFragment1

package a.b.c.fragmentmangers;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment1#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment1 extends Fragment {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public BlankFragment1() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment1.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment1 newInstance(String param1, String param2) {
BlankFragment1 fragment = new BlankFragment1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank1, container, false);
}
}

ItemFragment

package a.b.c.fragmentmangers;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import a.b.c.fragmentmangers.placeholder.PlaceholderContent;

/**
* A fragment representing a list of Items.
*/
public class ItemFragment extends Fragment {

// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;

/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemFragment() {
}

// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static ItemFragment newInstance(int columnCount) {
ItemFragment fragment = new ItemFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);

// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(PlaceholderContent.ITEMS));
}
return view;
}
}

MyItemRecyclerViewAdapter.java

package a.b.c.fragmentmangers;

import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import a.b.c.fragmentmangers.placeholder.PlaceholderContent.PlaceholderItem;
import a.b.c.fragmentmangers.databinding.FragmentItemBinding;

import java.util.List;

/**
* {@link RecyclerView.Adapter} that can display a {@link PlaceholderItem}.
* TODO: Replace the implementation with code for your data type.
*/
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {

private final List<PlaceholderItem> mValues;

public MyItemRecyclerViewAdapter(List<PlaceholderItem> items) {
mValues = items;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

return new ViewHolder(FragmentItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));

}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
}

@Override
public int getItemCount() {
return mValues.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mIdView;
public final TextView mContentView;
public PlaceholderItem mItem;

public ViewHolder(FragmentItemBinding binding) {
super(binding.getRoot());
mIdView = binding.itemNumber;
mContentView = binding.content;
}

@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:orientation="vertical"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="change"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_2"
android:text="replace"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/framelayout"
android:background="#00BCD4"/>

</LinearLayout>

fragment_blank1.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=".BlankFragment1">

<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

</FrameLayout>

fragment_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />

<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
</LinearLayout>

fragment_item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView 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:id="@+id/list"
android:name="a.b.c.fragmentmangers.ItemFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ItemFragment"
tools:listitem="@layout/fragment_item" />

Activity与Fragment通信

使用Bundle

MainActivity.java

@Override
public void onClick(View view){
switch(view.getId()){
case R.id.btn:
Bundle bundle = new Bundle();
bundle.putString("lele","lele");
BlankFragment1 bf = new BlankFragment1();
bf.setArguments(bundle);
replaceFragment(bf);
break;
}
}

BlankFragment1.java

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
String string = bundle.getString("lele");
Log.i("lele",string);
if(getArguments()!=null){
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PAEAM2);
}
}

fragment动态添加与管理的总结

Fragment与activity通信的接口方案

  • 原生方案:Bundle
  • Java语言中类与类之间通信常用方案:接口

MainActivity.java

package a.b.c.fragmentmangers;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn_2);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View view){
switch(view.getId()){
case R.id.btn:
Bundle bundle = new Bundle();
bundle.putString("lele","lele");
BlankFragment1(bundle);
bf.setFragmentCallback(new IFragmentCallback(){
@Override
public void sendMsgToActivity(String msg){
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
@Override
public String getMsgFromActivity(String msg){
return "hello, I am from MainActivity";
}

});
replaceFragment(bf);
break;

case R.id.btn_2:
replaceFragment(new ItemFragment());
break;
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.framelayout,fragment);
transaction.addToBackStack(null);
}
}

IFragmentCallback.java

package a.b.c.fragmentmangers;
public interface IFragmentCallback{
void sendMsgToActivity(String string);
String getMsgFromActivity(String msg);
}

BlankFragment1.java

package a.b.c.fragmentmangers;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment1#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment1 extends Fragment {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private View rootview;

public BlankFragment1() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment1.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment1 newInstance(String param1, String param2) {
BlankFragment1 fragment = new BlankFragment1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
String string = bundle.getString("lele");
Log.i("lele",string);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@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_blank1, container, false);
}
Button btn = rootview.findViewById(R.id.btn_3);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//fragmentCallback.sendMsgToActivity("hello, I`m from Fragment");
String message = fragmentCallback.getMsgFromActivity("null");
Toast.makeText(BlankFragment1.this.getContext(),message,Toast.LENGTH_SHORT).show();
}
});


return rootview;
}

private IFragmentCallback fragmentCallback;
public void setFragmentCallback(IFragmentCallback callback){
fragmentCallback = callback;
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:orientation="vertical"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="change"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_2"
android:text="replace"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/framelayout"
android:background="#00BCD4"/>

</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=".BlankFragment1">

<!-- TODO: Update blank fragment layout -->

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_3"
android:layout_gravity="center"
android:text="数据传递"/>

</FrameLayout>

fragment_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />

<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
</LinearLayout>

Fragment生命周期

onAttach()用来与Activity进行绑定,onCreate()对Bundle进行解析,onCreateView()进行ui进行解析,必须要重构的数据要在onResume()中获取,创建的时候从小到大,销毁的时候从大到小

加入些调试信息观察生命周期

BlankFragment1

package a.b.c.fragmentmangers;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment1#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment1 extends Fragment {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG = "BlankFragment1";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private View rootview;

public BlankFragment1() {
// Required empty public constructor

}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment1.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment1 newInstance(String param1, String param2) {
BlankFragment1 fragment = new BlankFragment1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
Log.d(TAG, "onAttach: ");
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
String string = bundle.getString("lele");
Log.i("lele",string);

if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
Log.d(TAG,"onCrate: ");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(rootview == null){
rootview = inflater.inflate(R.layout.frament_blank1,container,false);
}
Button btn = rootview.findViewById(R.id.btn_3);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//fragmentCallback.sendMsgToActivity("hello, I`m from Fragment");
String message = fragmentCallback.getMsgFromActivity("null");
Toast.makeText(BlankFragment1.this.getContext(),message,Toast.LENGTH_SHORT).show();
}
});
Log.d(TAG,"onCreateView:");
return rootview;
}

@Override
public void onResume(){
super.onResume();
Log.d(TAG,"onResume:");
}

@Override
public void onPause(){
super.onPause();
Log.d(TAG,"onPause");
}

@Override
public void onStop(){
super.onStop();
Log.d(TAG,"onStop");
}

@Override
public void onDestroyView(){
super.onDestroyView();
Log.d(TAG,"onDestroView");
}

@Override
public void onDestroy(){
super.onDestroy();
Log.d(TAG,"onDestory");
}





private IFragmentCallback fragmentCallback;
public void setFragmentCallback(IFragmentCallback callback){
fragmentCallback = callback;
}

}

Fragment生命周期注意事项‘

ViewPager2基本应用

MainActivity.java

package a.b.c.viewpagerandfragment;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

ViewPager2 viewPager = findViewById(R.id.viewPager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
}
}

ViewPagerAdaper.java

package a.b.c.viewpagerandfragment;

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 androidx.constraintlayout.widget.ConstraintLayout;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder>{
private List<String> titles = new ArrayList<>();
ViewPagerAdapter(){
titles.add("hhh");
titles.add("lelel");
titles.add("hhh");
titles.add("lelel");
titles.add("hhh");
titles.add("lelel");
titles.add("hhh");
titles.add("lelel");
titles.add("hhh");
titles.add("lelel");
}
@NonNull
@Override
public ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType){
return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager,parent,flase));

/*详细解释
LayoutInflater.from(parent.getContext())

LayoutInflater 是一个 Android 类,用于从 XML 布局文件中创建视图对象。from(parent.getContext()) 获取一个 LayoutInflater 实例,使用的是 parent 视图组的上下文 (Context)。

通过 parent.getContext() 获取 Context,因为 LayoutInflater 需要一个 Context 对象来访问资源并膨胀布局。

.inflate(R.layout.item_pager, parent, false)

inflate 方法用于将 XML 布局文件转换成实际的视图对象。这里,它将 R.layout.item_pager 布局文件中的视图膨胀成一个 View 对象。

R.layout.item_pager 是布局资源的 ID,代表你要膨胀的布局文件。item_pager.xml 中定义的视图将被加载到内存中。

parent 是 ViewGroup,它指定了布局的父视图组。在膨胀布局时,将这个 parent 传递进去可以确保正确设置视图的布局参数。

false 表示膨胀后的视图不会立即被附加到 parent 上。将其设置为 false 可以防止布局在膨胀时立刻附加到父视图,这样通常可以更好地控制视图的布局过程。

new ViewPagerViewHolder(...)

使用膨胀出来的 View 对象来创建一个新的 ViewPagerViewHolder 实例。ViewPagerViewHolder 是你定义的 RecyclerView.ViewHolder 子类,用于在 RecyclerView 中持有和管理视图。

在 ViewPagerViewHolder 的构造函数中,传入膨胀后的视图(itemView)用于初始化持有者的视图引用。

作用
这段代码的整体作用是创建一个新的 ViewPagerViewHolder 实例,并将其与通过 item_pager.xml 膨胀出的视图相关联。ViewPagerViewHolder 负责持有和管理 RecyclerView 中每个项的视图。在 onCreateViewHolder 方法中,你使用这段代码来为 RecyclerView 创建并返回一个新的视图持有者对象。
总结
膨胀布局:从 XML 布局文件 item_pager.xml 中膨胀出一个视图。
创建持有者:使用膨胀出的视图创建一个 ViewPagerViewHolder 实例。
返回持有者:将创建的视图持有者返回给 RecyclerView。
这样,RecyclerView 就可以使用这个视图持有者来显示和管理列表项。*/
}
@Override
public void onBindViewHolder(@NoNull viewPagerViewHold holder,int position){
holder.mTv.setText(tiltles.get(positon));
}
@Ovrride
public int getItemCount(){
return 10;
}
class ViewPagerViewHolder extends RecycleView.ViewHolder{
TextView mTv;
ConstraintLayout mContainer;
public ViewPagerViewHolder(@NoNull View itemView){
super(itemView);

mContainer = itemView.findViewById(R.id.container);
mTv = itemView.findViewById(R.id.tvTitle);
}
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewPager"
android:background="#03A9F4">

</androidx.viewpager2.widget.ViewPager2>

</LinearLayout>

item_pager.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
android:layout_height="match_parent"
android:id="@+id/tvTitle"
android:gravity="center"
android:textColor="#2196F3"
android:text="lele"
android:textSize="50dp"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

ViewPager2页面的切换

在color.xml文件中定义颜色

color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="red">#FF4411</color>
<color name="colorPrimary">#6200EE</color>
<color name="colorAccent">#03DAC5</color>
<color name="colorPrimaryDark">#3700B3</color>
</resources>

ViewPagerAdapter.java

package a.b.c.viewpagerandfragment;

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 androidx.constraintlayout.widget.ConstraintLayout;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends RecycleView.Adapter<ViewPagerAdater.ViewPagerViewHolder>{
private List<String> titles = new ArrayList<>();
private List<Integer> colors = new ArrayList<>();
ViewPagerAdapter(){
titles.add("1");
titles.add("2");
titles.add("3");
titles.add("4");
titles.add("5");
titles.add("6");
titles.add("7");
titles.add("8");
titles.add("9");
titles.add("10");

colors.add(R.color.white);
colors.add(R.color.colorAccent);
colors.add(R.color.black);
colors.add(R.color.red);
colors.add(R.color.white);
colors.add(R.color.colorPrimaryDark);
colors.add(R.color.white);
colors.add(R.color.colorAccent);
colors.add(R.color.red);
colors.add(R.color.colorAccent);
}
@NonNull
@Override
public ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGruop parent,int viewType){
return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager,parent,false));
}

@Override
public void onBindViewHolder(@NonNull ViewPagerViewHolder holder,int position){
holder.mTv.setText(titles.get(position));
holder.mContainer.setBackgroumdResource(colors.get(position));
}
@Override
public int getItemCount(){
return 0;
}
class ViewPagerViewHolder extends RecyclerView.ViwHolder{
TextView mTv;
ConstrainLayout mContainer;
public ViewPagerViewHolder(@NonNUll View itemView){
super(itemView);

mContainer = itemView.findViewById(R.id.container);
mTv = itemView.finViewById(R.id.tvTitle);
}
}
}

Fragment与ViewPager合集

MainActivity.java

package a.b.c.wechatpage;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity{
ViewPager2 viewPager;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ininPager();
}
private void initPager(){
viewPager = findViewById(R.id.id_viewpager);
ArrayList<Fragment> fragment=new ArrayList<>();
fragments.add(BlankFragment.newInstance("微信聊天"));
fragments.add(BlankFragment.newInstance("通讯录"));
fragments.add(BlankFragment.newInstance("聊天"));
fragments.add(BlankFragment.newInstance("发现"));
fragments.add(BlankFrament.newInstance("我"));

MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragment(),getLifecycle(),fragments);
viewPager.setAdapter(pagerAdapter);
}
}

MyFragmentPagerAdapter.java

public class MyFragmentPagerAdapter extends FragmentStateAdapter{
List<Fragment>fragmenList=new ArrayList<>();
public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager,@NonNull Lifecycle,List<Fragment>fragments){
super(fragmentManager,lifecycle);
fragmetnList=fragments;
}
@NonNull
@Override
public Fragment createFragment(int position){
return fragmentList.get(position);

}
@Override
public int getItemCount(){
return fragmentList.size();
}

BlankFragment.java


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;

public class BlankFragment extends Fragment{
View rootView;
private static final String ARG_TEXT = "param1";
private String mTextString;
public BlankFragment(){

}
public static BlanFragment 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){
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.seetText(mTextString);
}
}

activity_main.xml

注意:orientation要设置,否则无法正常显示

<?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:id="@+id/main"
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"
/>
</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:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="36sp"
android:id="@+id/text"
android:text="@string/hello_blank_fragment" />

</FrameLayout>

ViewPager+fragment模仿微信页面

android:layout_gravity: 控制视图相对于其父视图的位置。

android:gravity: 控制视图内部内容的位置和对齐方式。