Fragment
- Fragment是依赖于Activity的,不能独立存在的。
-
一个Activity里可以有多个Fragment。
-
一个Fragment可以被多个Activity重用。
-
Fragment有自己的生命周期,并能接收输入事件。
- 我们能在Activity运行时动态地添加或删除Fragment。
Fragment的生命周期
Fragment必须是依存于Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。
- onAttach(Activity); //当Activity与Fragment发生关联时调用
- onCreateView(LayoutInflater,ViewGroup,Bundle); //创建该Fragment的视图
- onActivityCreate(bundle); //当Activity的onCreate();方法返回时调用
- onDestoryView(); //与onCreateView相对应,当改Fragment被移除时调用
- onDetach(); //与onAttach()相对应,当Fragment与Activity的关联被取消时调用
Container.java:
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import com.example.helloworld.R; public class ContainerActivity extends AppCompatActivity { private AFragment aFragment; private BFragment bFragment; private Button mBtnChange; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_container); mBtnChange = findViewById(R.id.btn_change); mBtnChange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(bFragment == null){ bFragment = new BFragment(); } getSupportFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).commitAllowingStateLoss(); } }); //实例化AFragment aFragment = new AFragment(); //把AFragment添加到Activity中 getSupportFragmentManager().beginTransaction().add(R.id.fl_container,aFragment).commitAllowingStateLoss(); } }
activity_container:
<?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"> <Button android:id="@+id/btn_change" android:layout_width="match_parent" android:layout_height="50dp" android:text="更换Fragment" /> <FrameLayout android:id="@+id/fl_container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/btn_change"/> </RelativeLayout>
两个Fragment 分别为AFagment和BFragment
import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.helloworld.R; public class AFragment extends Fragment { private TextView mTvTitle; private Activity mActivity; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_a,container,false); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mTvTitle = view.findViewById(R.id.tv_title); } }
点击按钮 切换Fragment