java—如何在运行时在android studio创建的导航抽屉中设置默认片段

vkc1a9a2  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(368)

下面是 MainActivity 由android studio navigation drawer活动生成的类,其中包含3个名为home、gallery和slideshow的片段,以及如何在运行时更改默认片段

public class MainActivity extends AppCompatActivity {

  private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
        });

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_gallery, R.id.nav_slideshow,R.id.nav_home)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}
zvokhttg

zvokhttg1#

最初,必须在 navGraph 使用 app:startDestination 属性,否则会得到 RuntimeExceptionandroid.view.InflateException: Binary XML file line #10: Error inflating class fragment .
所以,您的问题的答案是:您不能以编程方式设置默认片段,因为您必须首先在xml中设置它。但您可以做的是从默认值导航 startDestination 另一个目标片段 onCreate() 方法,然后将默认片段显示给用户。
这个 NavController 负责在中的片段目的地之间导航 navGraph .
有几个重载版本的 navigate() 中的方法 NavController 类,允许您在片段之间导航。
例如,要将事务设置为gallery片段,可以将其id传递给 navigate() 方法

protected void onCreate(Bundle savedInstanceState) {
    ...
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    navController.navigate(R.id.nav_gallery);
...

相关问题