主文件和菜单

时间:2018-09-17 09:18:20

标签: java android android-studio menu navigation-drawer

不要通过扩展基本根文件(BaseActivity)中的活动来多次重复代码。我有两个活动菜单:一个主菜单和一个抽屉菜单。是否可以在单个页面上编写Java代码,而不必每次都重复它?

public class MyListSiteActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener  {

    // other code


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


    // Drawer menu
    drawerLayout = (DrawerLayout) findViewById(R.id.dlMenu);
    toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
    drawerLayout.addDrawerListener(toggle);
    toggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nvMenu);
    navigationView.setNavigationItemSelectedListener(this);

    // other code

    }



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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    //primary menu
    if (id == R.id.login) {
        Intent intentLogin = new Intent(this, Login.class);
        this.startActivity(intentLogin);
        return true;
    } else  if (id == R.id.setting){
        return true;
    }


    // drawer menu
    if (toggle.onOptionsItemSelected(item)){
        return true;
    }

    return super.onOptionsItemSelected(item);
    }


    // drawer menu
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch(item.getItemId()) {
        case R.id.insertSite:
            Intent intentSiteActivity = new Intent(this, InsertSiteActivity.class);
            startActivity(intentSiteActivity);
            return true;
        case R.id.myListSite:
            Intent intentMyListSite = new Intent(this, MyListSiteActivity.class);
            startActivity(intentMyListSite);
            return true;
        default:
            return false;
    }

    }

}

BaseActivity:

public class BaseActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;
    public ActionBarDrawerToggle toggle;

    // other code


    // other code

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

    // other code




    }


}

当我尝试将菜单代码放在BaseActivity的文件上时,它总是标记我错误。

0 个答案:

没有答案