项目自动选中

时间:2016-09-24 20:39:47

标签: java android

如何在打开页面时自动选择项目(" R.id.nav_code"例如)?

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_code) {
    fragmentManager.beginTransaction()
            .replace(R.id.content_frame
                    , new code())
            .commit();
} else if (id == R.id.nav_documentation) {
    fragmentManager.beginTransaction()
            .replace(R.id.content_frame
                    , new documentation())
            .commit();
} else if (id == R.id.nav_number) {
    fragmentManager.beginTransaction()
            .replace(R.id.content_frame
                    , new number())
            .commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
    return true;
}

1 个答案:

答案 0 :(得分:1)

如果您想在每次活动开始时启动默认片段,请将此代码添加到您的活动中onCreate方法

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

FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
code_Fragment code=new code_Fragment(); //Create Object Of your Fragment
transaction.replace(R.id.FragmentLoginRegistration,code);
transaction.commit();
}