如何在android中创建自定义启动活动方法?

时间:2017-01-05 18:27:40

标签: android methods start-activity

我想创建一个启动多个活动的方法。我在每个按钮上都设置了setOnClickListener。我已经实现了onClick()方法,如下所示:

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.firstActivityButton:
            Intent i1 = new Intent(getApplicationContext(), FirstActivity.class);
            startActivity(i1);
            break;

        case R.id.secondActivityButton:
            Intent i2 = new Intent(getApplicationContext(), SecondActivity.class);
            startActivity(i2);
            break;

        //and so on
    }
}

我想在每个case中使用这样的方法:startSpecificActivity(FirstActivity.class)这是我的方法:

public void startSpecificActivity(Context context) {
    Intent intent = new Intent(getApplicationContext(), context.class);
    startActivity(intent);
}

1 个答案:

答案 0 :(得分:5)

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.firstActivityButton:
            startSpecificActivity(FirstActivity.class);
            break;

        case R.id.secondActivityButton:
            startSpecificActivity(SecondActivity.class);
            break;

        // And so on
    }
}

创建这样的方法,其中Class<?>是通用类对象持有者,?是通配符:

public void startSpecificActivity(Class<?> otherActivityClass) {
    Intent intent = new Intent(getApplicationContext(), otherActivityClass);
    startActivity(intent);
}

我还鼓励使用当前活动的contextYourActivityName.this,而不是getApplicationContext()