自定义导航抽屉中setOnClickListener的最佳实践

时间:2017-07-29 06:34:40

标签: android onclicklistener

我在我的应用中使用自定义导航抽屉。对于切换活动,我为每个按钮使用setOnClickListener。但我认为这可能会占用大量内存,因为每次都会在每个活动中加载相同的代码。那么有没有有效的方法来处理像switch case这样的菜单的点击监听器?

我的导航项目点击代码。

 Button oneButton = (Button) findViewById(R.id.nav_one);
    Button twoButton = (Button) findViewById(R.id.nav_two);
    Button threeButton = (Button) findViewById(R.id.nav_three);
    Button fourButton = (Button) findViewById(R.id.nav_four);
    Button fiveeButton = (Button) findViewById(R.id.nav_five);

        oneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        Intent firstIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(firstIntent);
        }
        });

        twoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        Intent secondIntent = new Intent(getApplicationContext(), SecondActivity.class);
        startActivity(secondIntent);

        }
        });

        threeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        Intent threeButton = new Intent(getApplicationContext(), ThirdActivity.class);
        startActivity(thirdIntent);

        }
        });

        threeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        Intent fourButton = new Intent(getApplicationContext(), FouthActivity.class);
        startActivity(fourthIntent);

        }
        });

        fourButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        Intent fiveButton = new Intent(getApplicationContext(), FifthouthActivity.class);
        startActivity(fifthIntent);
        }
        });

1 个答案:

答案 0 :(得分:0)

使用此方法,它可能会帮助您

别忘了添加此

 public static void main(String[] args) {
    new SimpleThread().start();
    new SimpleThread().start();
}