fragment加载方式
1. 静态加载( 不行,没有 试出来)
2. 动态加载
1. Fragent使用
效果图:
Java代码 MainActivity:
***********************************************************************************************************************
public class MainActivity extends AppCompatActivity {
LinearLayout mainContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainContext = findViewById(R.id.mainContext);
AFragment aFragment=new AFragment();
FragmentManager manager=getFragmentManager();
// Fragment 添加事务
FragmentTransaction transaction= manager.beginTransaction();
// 把Fragment 添加到指定容器中,提交才有效果
transaction.add(R.id.mainContext,aFragment).commit();
}
public void f1(View view){
AFragment aFragment=new AFragment();
FragmentManager manager=getFragmentManager();
// Fragment 添加事务
FragmentTransaction transaction= manager.beginTransaction();
// 把Fragment 添加到指定容器中,提交才有效果
transaction.replace(R.id.mainContext,aFragment).commit();
}
public void f2(View view){
BFragment bFragment=new BFragment();
FragmentManager manager=getFragmentManager();
// Fragment 添加事务
FragmentTransaction transaction= manager.beginTransaction();
// 把当前操作添加到回退栈,点击back键盘可以回退到上一个Fragment
transaction.addToBackStack(null);
// 把Fragment 添加到指定容器中,提交才有效果
// 首先 remove,然后在add
transaction.replace(R.id.mainContext,bFragment).commit();
// transaction.remove(bFragment).commit();
}
}
***********************************************************************************************************************
activity_main.xml
BFragment
public class BFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = View.inflate(getActivity(),R.layout.afragment,null);
Button btn1 = view.findViewById(R.id.btn1);
btn1.setTextColor(Color.BLACK);
btn1.setText("BFragment");
return view;
}
}
afragment.xml
fragment生命周期:
启动应用:onAttach onCreate onCreateView onActivityCreated onStart onResume
HOME键:onPause
回到应用: onStart onResume
切换BFagment: onPause onStop onDestroyView
退出应用:onPause onStop onDestroyView onDetach onDestroy
作者:小置同学