在Android studio中的导航栏中替换片段时出错

问题描述 投票:0回答:2

我在android studio中使用navbar。我正在尝试通过getSupportFragmentManager()。beginTransaction()。replace()来替换片段,但它不起作用并且不断给我错误。这是代码:

public class UserNavbar extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

private DrawerLayout mydrawerlayout;
private ActionBarDrawerToggle atoggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_navbar);

    mydrawerlayout = (DrawerLayout)findViewById(R.id.drawer_layout);

    atoggle = new ActionBarDrawerToggle(this,mydrawerlayout,R.string.open,R.string.close);  //Done
    mydrawerlayout.addDrawerListener(atoggle);
    atoggle.syncState();  
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
  switch (menuItem.getItemId()){
        case R.id.home:
            getSupportFragmentManager().beginTransaction().replace(R.id.frame, new User_Home_Fragment()).commit();
            break;
        case R.id.personalinformation:
            getSupportFragmentManager().beginTransaction().replace(R.id.frame, new Personal_Info_Frag()).commit();
            break;
        case R.id.settings:

getSupportFragmentManager().beginTransaction().replace(R.id.frame, new Settings_Frag()).commit();
            break;
}
mydrawerlayout.closeDrawer(GravityCompat.START);
    return true;
}}

这是错误:Error Message

开发了User_Home_Fragment(),Personal_Info_Frag()和Settings_Frag()。如果需要,我也会发布它们。

如果有人有任何建议,我会很感激。问候

java android android-fragments android-navigation-drawer
2个回答
1
投票

我想你错过了新的关键字因为becase replace方法有两个参数,第一个是容器id,第二个是片段实例。

getSupportFragmentManager().beginTransaction().replace(R.id.frame, new User_Home_Fragment()).commit();

0
投票

请在致电你的片段之前写下新的关键字。胃内

new User_Home_Fragment()
© www.soinside.com 2019 - 2024. All rights reserved.