在运行中替换片段

时间:2014-05-28 09:15:14

标签: android android-fragments

Android Studio 0.5.8

您好,

我有一个活动(MainActivity)将托管2个片段(ListAddressBookFragmentAddAddressBookFragment)(一次只有一个)。初始片段将是ListAddressBookFragment,并且会在MainActivity onCreate被调用时膨胀。

/* MainActivity.java */
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    /* Add and display fragment */
    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment fragment = fragmentManager.findFragmentById(R.id.flFragmentContainer);

    /* Create new fragment if this hasn't already been done */
    if(fragment == null) {
        fragment = new ListAddressBookFragment();
        fragmentManager.beginTransaction()
                .add(R.id.flFragmentContainer, fragment)
                .commit();
    }
}

ListAddressBookFragment我有一个选项菜单,可以添加新的地址簿项目。所以这将调用MainActivity。所以我想将ListAddressBookFragment替换为AddAddressBookFragment。但是,因为上面的代码是硬编码的,我想知道反正这样做了吗?

/* ListAddressBookFragment.java */
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.new_addressbook) {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

非常感谢任何建议,

2 个答案:

答案 0 :(得分:1)

为什么不将数据传递给MainActivity以指示您希望活动进入的模式?

intent.putExtra("mode", "addressbook");

在MainActivity中,您可以执行以下操作。

    String mode = (String)getIntent().getStringExtra("mode");
    if ("addressbook".equals(mode)) {
    // Address book fragment
    } else {
    // ListAddressBookFragment
    }

祝你好运

答案 1 :(得分:1)

我建议你阅读这篇文章,Communicating with fragments

基本上,你需要打电话

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);

另外,请考虑在活动实现的片段中使用接口。