片段与其他片段重叠

时间:2016-02-26 07:58:42

标签: android android-fragments view fragment fragmenttransaction

在我尝试在片段之间切换时,我看到它们堆叠在一起。我知道这应该通过动态添加片段来修复,但是当我尝试这个时,问题仍然存在。

这是我的SocksAndUndies类的顶部,以及我的onCreate方法(这是我的FragmentActivity,包含我的NavigationView):

public class SocksAndUndies extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
        FragmentJSON fragmentJSON;
        FragmentTransaction ft;

protected void onCreate(Bundle savedInstanceState) {


  super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_socks_and_undies);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    fragmentJSON = new FragmentJSON();
    ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.socksAndUndies, fragmentJSON, "fragmentJSON");
    ft.commit();
}

这是我用来更改碎片的方法:

public boolean onNavigationItemSelected(MenuItem item) {
        FragmentTransaction ft;
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_gallery) {
            EventsFragment eventsFragment = new EventsFragment();
            ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.socksAndUndies, eventsFragment, "EventsFragment");
        } else if (id == R.id.nav_slideshow) {
            ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.socksAndUndies, fragmentJSON, "fragmentJSON");
        )
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;    
}

这是我的观点:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:id="@+id/socksAndUndies"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

我可以在这里看到一些问题,但不知道他们是否与您指出的问题有关。 在onNavigationItemSelected方法中,您缺少结束括号和ft.commit命令。 这是什么样的:

public boolean onNavigationItemSelected(MenuItem item) {
    FragmentTransaction ft;
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    ft = getSupportFragmentManager().beginTransaction();
    if (id == R.id.nav_gallery) {
        EventsFragment eventsFragment = new EventsFragment();            
        ft.replace(R.id.socksAndUndies, eventsFragment, "EventsFragment");
    } else if (id == R.id.nav_slideshow) {
        ft.replace(R.id.socksAndUndies, fragmentJSON, "fragmentJSON");
    }
    ft.commit();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;    
}