我在同一活动下的两个片段一个接一个地显示在另一个之上



我有一个活动:

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

设置片段

您建议如何设计和实现它?正确的方法是什么?

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

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

最新更新