我在相同活动下的两个片段一个在另一个上面显示

时间:2015-01-31 21:36:28

标签: android android-layout android-fragments android-fragmentactivity

我有一项活动:

public class MainActivity_with_Fragment extends RoboFragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new SettingsFragment())
                    .add(R.id.container, new AddReminderFragment())
                    //.add(R.id.container, new ReadRemindersFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
        return true;
    }

    @Override
    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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这种布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:id="@+id/container"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.example.stopcall.app.activities.dele_MainActivity2_with_Fragment"
             tools:ignore="MergeRootFrame"/>

我希望它分别托管3个片段(每次只显示一个片段):

Item添加到数据库片段

从数据库中读取Items

设置片段

您如何建议设计和实施此功能?什么是正确的方法?

1 个答案:

答案 0 :(得分:0)

您要在同一容器中添加两个片段。如果您只需要一次显示一个,请执行此操作。

getSupportFragmentManager().beginTransaction()
   .add(R.id.container, new SettingsFragment()).commit();

getSupportFragmentManager().beginTransaction(
   .replace(R.id.container, new AddReminderFragment()).commit();

但是如果你需要同时展示它们,那么创建一个新容器(比如R.id.container_two)并执行此操作

getSupportFragmentManager().beginTransaction()
     .add(R.id.container, new SettingsFragment()).commit();
getSupportFragmentManager().beginTransaction()
    .add(R.id.container_two, new AddReminderFragment()).commit();