我是否需要在每个活动中实现DrawerItemClickListener类?

时间:2017-06-28 20:47:26

标签: android navigation-drawer

目前,我正在克隆每个活动中的代码段,以便在左侧获得相同的导航栏。显然,如果我改变任何东西,那就涉及繁琐的编辑,我必须编辑它的所有实例。所以我确信有一种更聪明的方法可以做到这一点,即只有一个位置,只是在每个活动中引用它?

    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            switch(position) {

                case 0:

                    Intent intentMain = new Intent(CardView.this, MainActivity.class);
                    startActivity(intentMain);

                    break;

                case 1:

                    Intent intentFront = new Intent(CardView.this, FrontPage.class);
                    startActivity(intentFront);

                    break;
                 ...
                 ...
                 ...

1 个答案:

答案 0 :(得分:0)

您可以使用DrawerItemClickListener类创建单独的文件,而不是在每个活动中创建实例。

public class DrawerItemClickListener implements ListView.OnItemClickListener 
{
    private Activity mActivity;
    public DrawerItemClickListener(Activity activity) {
       mActivity = activity;
    }        

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch(position) {

            case 0:

                Intent intentMain = new Intent(mActivity, MainActivity.class);
                mActivity.startActivity(intentMain);

                break;

            case 1:

                Intent intentFront = new Intent(mActivity, FrontPage.class);
                mActivity.startActivity(intentFront);

                break;
             ...
             ...
             ...

活动中:

mDrawerItemClickListener  = new DrawerItemClickListener(this)