问题描述
我创建了一个选项卡式活动,所以我已经做了很多事情.我跟随了一个教程,当单击一个抽屉项目时,将其更改为另一个片段.现在,在初始化应用程序时,我需要将 MainFragment
设置为默认值.我实际上不知道此刻正在发生什么.
I've created a tabbed activity, so many things are already done for me. I followed up a tutorial to, when clicking a drawer item, change to another fragment. Now, I need to, when initializing my app, for my MainFragment
to be the default. I actually do not know what's showing up at the moment.
下面是负责处理片段更改的 MainActivity
的代码:
Below's the code of MainActivity
that's responsible for handling the fragment change:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
setFragmentTransaction(new MainFragment(), "Dashboard");
break;
case R.id.nav_accounts:
setFragmentTransaction(new AccountFragment(), "Accounts");
break;
case R.id.nav_categories:
break;
case R.id.nav_transactions:
break;
case R.id.nav_reports:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setFragmentTransaction(Fragment fragment, String title) {
setTitle(title);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
我尝试设置一个默认
,但是它没有任何影响.
I tried setting up a default
, but it didn't affect anything.
推荐答案
在 onCreate
的底部添加 setFragmentTransaction(new MainFragment(),"Dashboard");
.那应该加载您的主要片段.
Add setFragmentTransaction(new MainFragment(), "Dashboard");
to the bottom of onCreate
. That should get your main fragment loaded.
这篇关于配置启动应用程序时首先显示的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!