fragment的循环添加
···mainactivity类
private RadioButton rb1;
private RadioButton rb2;
private RadioButton rb3;
private RadioButton rb4;
private RadioGroup rg;
private ArrayList<Fragment> fragments = new ArrayList<>();
private LinearLayout lin_act;
private int index = 0;
private void initData() {
Mainpresenter mainpresenter = new Mainpresenter();
mainpresenter.Attchview(this);
mainpresenter.getData();
}
//加载视图
private void initView() {
lin_act = (LinearLayout) findViewById(R.id.lin_act);
rb1 = (RadioButton) findViewById(R.id.rb1);
rb2 = (RadioButton) findViewById(R.id.rb2);
rb3 = (RadioButton) findViewById(R.id.rb3);
rb4 = (RadioButton) findViewById(R.id.rb4);
rg = (RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
switch (checkedId) {
case R.id.rb1:
index = 0;
break;
case R.id.rb2:
index = 1;
break;
case R.id.rb3:
index = 2;
break;
case R.id.rb4:
index = 3;
break;
}
showFragment(index);
}
});
}
/**
* eventbus的事件订阅者处理事件
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void writeEventBus(){
}
@Override
public void CallBackFragments(ArrayList<Fragment> fragments) {
this.fragments = fragments;
addFragment(fragments);
showFragment(index);
}
private void showFragment(int index) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
for (int i = 0; i < fragments.size(); i++) {
transaction.hide(fragments.get(i));
}
transaction.show(fragments.get(index));
transaction.commit();
}
private void addFragment(ArrayList<Fragment> fragments) {
for (int i = 0; i < fragments.size(); i++) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.lin_act, fragments.get(i));
transaction.commit();
}
}
···另一个类
public class Mainpresenter extends BasePresenter<MainView> {
private ArrayList<Fragment> fragments;
public void getData() {
//四个fragment
CartFragment cartFragment = new CartFragment();
ClassifyFragment classifyFragment = new ClassifyFragment();
HomeFragment homeFragment = new HomeFragment();
MeFragment meFragment = new MeFragment();
fragments = new ArrayList<>();
fragments.add(homeFragment);
fragments.add(classifyFragment);
fragments.add(cartFragment);
fragments.add(meFragment);
getAttchview().CallBackFragments(fragments);
}
}