动态加载原理


利用FragmentManager来添加一套Fragment事务,最后通过commit提交该事务来执行对Fragment的相关操作。

FragmentManager fragmentmanager = getFragmentManager();
FragmentTransaction beginTransaction = fragmentmanager.beginTranaction();

具体步骤


1.创建Fragment类

public class Fragment2 extends Fragment {
private TextView tv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_1,container,false);
tv= (TextView) view.findViewById(R.id.textview);
tv.setText("动态加载");
return view;
}
}

2.在Activity中启用事务

mbutton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment2 fragment2=new Fragment2();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame,fragment2);
fragmentTransaction.commit();
}
});

需要注意的是,由于Android Studio中Activity默认继承AppCompatActivity,所以在申请FragmentManager时,需要用getSupportFragmentManager()方法来获取。

3.利用addToBackStack实现回退功能

addToBackStack方法可以实现点击返回键时,回到上一个Fragment状态的效果。

05-11 11:37