在我尝试在片段之间进行切换时,我看到它们相互堆叠。我知道应该通过动态添加片段来解决此问题,但是当我尝试这样做时,问题仍然存在。
这是我的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>
最佳答案
我在这里可以看到一些问题,但不知道它们是否与您指出的问题有关。
在您的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;
}
关于android - fragment 与其他 fragment 重叠,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35646393/