静态加载
<fragment android:name="com.example.serviceapplication.fragment.TestFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/send_msg_btn"
android:id="@+id/fragement1" />
静态加载直接注册在布局的xml文件里。需要注意,要指定frament的类型<android:name>和id<android:id>。
动态加载
动态加载的实现方式通常是,先在xml文件里静态注册一个空的view,再将这个空的view替换成fragment实例。
先搞个壳:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/change_btn"/>
用java代码动态替换:
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
生命周期
fragment的生命周期与activity类似,但是fragment必须依附于activity存在,因此fragment必须额外能够判断自身与activity的关系,所以会有onAttach()与onDetach()
onAttach(): 当 Fragment 与 Activity 关联时调用。
onCreate(): 当 Fragment 创建时调用。
onCreateView(): 创建 Fragment 的视图层次结构时调用。
onActivityCreated(): 当与 Fragment 相关联的 Activity 完成 onCreate() 方法后调用。
onStart(): 当 Fragment 可见时调用。
onResume(): 当 Fragment 可交互时调用。
onPause(): 当 Fragment 失去焦点但仍可见时调用。
onStop(): 当 Fragment 不再可见时调用。
onDestroyView(): 当 Fragment 的视图层次结构被销毁时调用。
onDestroy(): 当 Fragment 被销毁时调用。
onDetach(): 当 Fragment 与 Activity 解除关联时调用。
Fragment通信
fragment与frament通信:
同一个activity里的frament之间通信很简单,因为他们可以互相持有。
能够互相持有的原因是,frament里可以通过getActivity()获取当前所在的activity,并进一步获取到该activity里面的其他frament。包括activtiy里其他暴露出的组件,都可以进行通信操作。
activity与frament通信:
安卓系统提供了一个机制,在创建frament的时候可以给它传递一个bundle,bundle里面存放数据即可。
activity里创建frament并传递数据bundle:
private void initView() {
mChangeFragmentBtn = this.findViewById(R.id.change_btn);
mChangeFragmentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("msg", "fragment1");
BlankFragment blankFragment = new BlankFragment();
// 给fragment传递参数
blankFragment.setArguments(bundle);
replaceFragment(blankFragment);
}
});
}
在fragment里面读取:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
Toast.makeText(getContext(), bundle.getString("msg"), Toast.LENGTH_SHORT).show();
}
}
由于frament一定被activity持有,所以activtiy可以通过注册listener的方式来获取frament的回调。
实例
可以将fragment和viewpager结合,做一个类似于微信主页的activity。
MainActivity:
package com.example.fragmentapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.fragmentapplication.fragment.BlankFragment;
import com.example.fragmentapplication.fragmentviewpager.FragmentViewPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ViewPager2 mViewPager;
View tab1, tab2, tab3, tab4;
View currentTab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initTabView();
}
private void initTabView() {
tab1 = this.findViewById(R.id.bottom_tab_chat);
tab1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(0);
}
});
tab2 = this.findViewById(R.id.bottom_tab_game);
tab2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(1);
}
});
tab3 = this.findViewById(R.id.bottom_tab_social);
tab3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(2);
}
});
tab4 = this.findViewById(R.id.bottom_tab_user);
tab4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(3);
}
});
currentTab = tab1;
currentTab.setSelected(true);
}
private void initView() {
mViewPager = this.findViewById(R.id.main_viewpager);
List<Fragment> fragmentList = new ArrayList<>();
fragmentList.add(new BlankFragment());
fragmentList.add(new BlankFragment());
fragmentList.add(new BlankFragment());
fragmentList.add(new BlankFragment());
FragmentViewPagerAdapter pagerAdapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragmentList);
mViewPager.setAdapter(pagerAdapter);
mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
setBottomTabSelected(position);
}
});
}
private void setBottomTabSelected(int position) {
currentTab.setSelected(false);
switch (position) {
case 0:
tab1.setSelected(true);
currentTab = tab1;
break;
case 1:
tab2.setSelected(true);
currentTab = tab2;
break;
case 2:
tab3.setSelected(true);
currentTab = tab3;
break;
case 3:
tab4.setSelected(true);
currentTab = tab4;
break;
}
}
}
FragmentViewPagerAdapter:
package com.example.fragmentapplication.fragmentviewpager;
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 FragmentViewPagerAdapter extends FragmentStateAdapter {
List<Fragment> mFragmentList = new ArrayList<>();
public FragmentViewPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle, List<Fragment> fragments) {
super(fragmentManager, lifecycle);
mFragmentList = fragments;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return mFragmentList.get(position);
}
@Override
public int getItemCount() {
return mFragmentList.size();
}
}
底部导航:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="@color/gray">
<LinearLayout
android:id="@+id/bottom_tab_chat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/tab_image_chat"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@color/black"/>
<TextView
android:id="@+id/tab_text_chat"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:text="聊天"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/bottom_tab_game"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/tab_image_game"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@color/black"/>
<TextView
android:id="@+id/tab_text_game"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:text="游戏"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/bottom_tab_social"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/tab_image_social"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@color/black"/>
<TextView
android:id="@+id/tab_text_socail"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:text="社区"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/bottom_tab_user"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/tab_image_user"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@color/black"/>
<TextView
android:id="@+id/tab_text_user"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:text="个人"
/>
</LinearLayout>
</LinearLayout>
主布局:
<?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:id="@+id/main_viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include layout="@layout/bottom_layout"/>
</LinearLayout>