Fragment搭建

FragmentManager+Fragment实现点击切换
主要利用了Fragment在主内容界面对Fragment的add,hide等事务操作。
public class TestTabActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
private FragmentManager mFragmentManager;
private TabOneFragment tabOneFragment = null;
private TabOneFragment tabTwoFragment = null;
private TabOneFragment tabThreeFragment = null;

public static void launch(Context context) {
    Intent intent = new Intent(context, TestTabActivity.class);
    context.startActivity(intent);
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_tab);
    RadioGroup radio_bottom = findViewById(R.id.radio_bottom);
    mFragmentManager = getFragmentManager();
    setTabSelection(0);
    radio_bottom.setOnCheckedChangeListener(this);
}

/**
 * 将所有的Fragment都置为隐藏状态。
 * 用于对Fragment执行操作的事务
 */
private void hideFragments(FragmentTransaction transaction) {
    if (tabOneFragment != null) {
        transaction.hide(tabOneFragment);
    }
    if (tabTwoFragment != null) {
        transaction.hide(tabTwoFragment);
    }
    if (tabThreeFragment != null) {
        transaction.hide(tabThreeFragment);
    }
}

private void setTabSelection(int index) {
    // 开启Fragment事务
    FragmentTransaction transaction = mFragmentManager.beginTransaction();
    hideFragments(transaction);
    switch (index) {
        case 0:
            if (tabOneFragment == null) {
                tabOneFragment = TabOneFragment.newInstance("第一个");
                transaction.add(R.id.id_content, tabOneFragment);
            } else {
                transaction.show(tabOneFragment);
            }
            break;
        case 1:
            if (tabTwoFragment == null) {
                tabTwoFragment = TabOneFragment.newInstance("第二个");
                transaction.add(R.id.id_content, tabTwoFragment);
            } else {
                transaction.show(tabTwoFragment);
            }
            break;
        case 2:
            if (tabThreeFragment == null) {
                tabThreeFragment = TabOneFragment.newInstance("第三个");
                transaction.add(R.id.id_content, tabThreeFragment);
            } else {
                transaction.show(tabThreeFragment);
            }
            break;
    }
    transaction.commit();
}

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
    switch (checkedId) {
        case R.id.radio_home:
            setTabSelection(0);
            break;
        case R.id.radio_center:
            setTabSelection(1);
            break;
        case R.id.radio_manager:
            setTabSelection(2);
            break;
    }
}

}

你可能感兴趣的:(Fragment搭建)