2016-02-26 182 views
1

在我嘗試切換片段之間,我看到它們堆疊在一起。我知道這應該通過動態添加片段來解決,但是當我嘗試這些時,問題依然存在。片段重疊其他片段

這是我的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> 

回答

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;  
} 
+0

對此深感抱歉,我在我的代碼的那些事,我插入這個SNIPPIT到我的代碼,並在它之前也做了同樣的方式表現。不用找了。 –