Fragment作为Android最基本,最重要的基础概念之一,在开发中经常会和他打交道。使用FragmentManager实现fragment切换已经无法满足市场的需求,当存在多个同种业务的fragment的时,需要使用fragment嵌套,一个activity对应多个fragment,在其中一个fragment中加载同种业务的fragment。
退回栈
ContentFragment fragment = new ContentFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fl_content,fragment); ft.addToBackStack(“name”); ft.commit();
清空退回栈
FragmentManager fm= getFragmentManager(); int count = fm.getBackStackEntryCount(); for (int i = 0; i < count; ++i) { fm.popBackStack(); }
如下实例进行activity通过setArguments发送数据
public void click(View view) { //取到输入的值 String string = editText.getText().toString(); //创建fragment对象 ShowContextFragment showContextFragment = new ShowContextFragment(); //创建bundle Bundle bundle = new Bundle(); bundle.putString("key",string); //给fragment对象赋值 showContextFragment.setArguments(bundle); //动态修改fragment fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.linear_layout_id,showContextFragment); fragmentTransaction.commit(); }
fragment通过getArguments获得数据
public class ShowContextFragment extends Fragment { private TextView textView; public ShowContextFragment() { } //现在text里面的值是"hello_blank_fragment",思路就是拿到控件,重新赋值即可. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflate = inflater.inflate(R.layout.fragment_show_context, container, false); //1 拿控件 textView = inflate.findViewById(R.id.context_tv_id); //2 给控件赋值 Bundle arguments = getArguments(); if(arguments != null){ //第一次启动一定为null,所以要判断一下 String key = arguments.getString("key"); textView.setText(key); } return inflate; } }