动态加载fragment,不需要适配器,也不需要TabLayout。使用一个容器,但是需要 windowManager进行管理。管理方法不太灵活。如果要有效管理需要实时获取position。我这里为少一些代码,让思路更清晰,采取把所有需要的fragment一次性全部创建出来操作的原始方法,有点浪费资源,特别是在fragment比较多的时候。所有要选好使用条件。
一、MyFragment
/**
* A simple {@link Fragment} subclass.
*/
public class MyFragment extends Fragment {
private TextView textView;
public MyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my, container, false);
initView(view);
return view;
}
private void initView(View view) {
String title= (String) getArguments().get("title");
textView= (TextView) view.findViewById(R.id.txt_title);
textView.setText(title);
}
}
二、
/**
* 动态加载fragment,不需要适配器
*/
public class FrameActivity extends AppCompatActivity implements View.OnClickListener {
private TextView[] tabs;
private Fragment[] fragments;
private int[] RES_TAB_ID = {R.id.txt_tab1, R.id.txt_tab2, R.id.txt_tab3, R.id.txt_tab4};
private String[] titles = {"天九", "地八", "人七", "和五"};
private int position;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame);
initView();
}
/**
* 初始化
*/
private void initView() {
tabs=new TextView[RES_TAB_ID.length];
fragments=new Fragment[RES_TAB_ID.length];
Bundle bundle;
for (int i = 0; i < RES_TAB_ID.length; i++) {
tabs[i]= (TextView) findViewById(RES_TAB_ID[i]);
tabs[i].setOnClickListener(this);//添加监听
//创建fragment
//由于没有使用TabLayout,我们采取简单的管理,一次性全部创建出来
//不过如果fragment比较多,建议写几个方法操作position,第一次使用的时候再创建,节省资源
fragments[i] = new MyFragment();
bundle = new Bundle();
bundle.putString("title", titles[i]);
fragments[i].setArguments(bundle);
}
loadFragments();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.txt_tab1:
position = 0;
break;
case R.id.txt_tab2:
position = 1;
break;
case R.id.txt_tab3:
position = 2;
break;
case R.id.txt_tab4:
position = 3;
break;
default:
break;
}
switchFragment(position);//切换
}
/**
* 一次性装载fragment
*/
private void loadFragments() {
FragmentManager fragmentManager = getSupportFragmentManager();//获取fragment管理器
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//获取事务
for (Fragment f : fragments) {
fragmentTransaction.add(R.id.frame_container, f, f.getClass().getName());
fragmentTransaction.hide(f);//加载后隐藏
}
fragmentTransaction.show(fragments[0]);//显示第一个
fragmentTransaction.commit();
}
/**
* 切换显示fragment
*/
private void switchFragment(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();//获取fragment管理器
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//获取事务
//隐藏所有
for (Fragment f : fragments) {
fragmentTransaction.hide(f);
}
//显示当前
fragmentTransaction.show(fragments[position]);
fragmentTransaction.commit();
}
}