Reputation: 39
In my attempt to switch between fragments, I am seeing them stack on top of one another. I know this is supposed to be fixed by dynamically adding fragments, but when I tried that, the problem persisted.
This is the top of my SocksAndUndies Class, and my onCreate method (Which is my FragmentActivity, containing my 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();
}
This is the method which I use to change Fragments:
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;
}
This is my View:
<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>
Upvotes: 1
Views: 116
Reputation: 602
I can see a few problems here, don't know if they're related with the one you pointed out though.
In your onNavigationItemSelected
method, you are missing a closing bracket and an ft.commit
command.
Here is what that would look like:
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;
}
Upvotes: 2