简体   繁体   English

如何创建启动活动的方法?

[英]How to create a method to start an activity?

I have a switch case that starts different activities depending on user selection. 我有一个开关盒,可以根据用户选择启动不同的活动。 I do not want to keep repeating the code for creating an intent like this: 我不想继续重复用于创建这样的意图的代码:

switch(choice) {
    case "option1":
        Intent intent = new Intent(context, MyActivity1.class);
    case "option2":
        Intent intent = new Intent(context, MyActivit2.class);
}

I want to create a function where I can pass the context and my activity like: 我想创建一个函数,可以在其中传递上下文和活动,例如:

private void startMyActivity(Context ctx, Type what_do_I_pass_here) {
    Intent intent = new Intent(context, Type.class);
    startActivity(intent);
}

I have tried 我努力了

private void startMyActivity(Context ctx,Class<Activity> cls)

but it's not working 但它不起作用

Try this code: 试试这个代码:

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

Usage: 用法:

startSpecificActivity(MyActivity1.class);

you have to define function like this 你必须定义这样的功能

public void startActivity(Context ctx, Class<?> activityClass) {
    Intent intent = new Intent(ctx, activityClass);
    startActivity(intent);
}

and you can call it like this 你可以这样称呼它

startActivity(this, MainActivity.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM