我已經創建了一個選項卡式活動,所以已經爲我完成了很多事情。當我點擊一個抽屜項目時,我跟隨了一個教程,轉到另一個片段。現在,我需要在初始化我的應用程序時將我的MainFragment
設置爲默認值。我其實並不知道目前出現的情況。配置一個片段,當應用程序啓動時首先顯示
下面是的MainActivity
這是負責處理片段更改代碼:
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();
}
}
我試圖建立一個default
,但它並沒有造成任何影響。
這聽起來像你需要添加額外的'setFragmentTransaction(new MainFragment(),「Dashboard」);'到'onCreate'的底部。你嘗試過嗎? –
我簡直不敢相信。可能不是最好的,但它的工作。請寫一個答案,我會標記爲正確和投票。 – mfgabriel92
我很高興能幫到你! –