Android: Dynamically starting an activity

2019-07-28 11:07发布

I would like to dynamically start an activity based on the previous activity's input. I have input a string through the previous activity, the only thing is this specific code throws the error

cannot resolve constructor 'Intent(com.MentalMathWorkout.EasyCountDown, java.lang.String)'

Is there a way to make this work?

public class EasyCountDown extends AppCompatActivity {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ecd);

    Intent intent = getIntent();
    String test = intent.getStringExtra(MainActivity.TEST_TYPE);
    String cstring = ".class";
    final String activity = test.concat(cstring);

    Intent intent = new Intent(EasyCountDown.this, activity);
    startActivity(intent); //Start test
}

2条回答
Animai°情兽
2楼-- · 2019-07-28 11:41

I have a class on here:

com.yasinkacmaz.newproject.activity.ProfileActivity

My test string like that:

"com.yasinkacmaz.newproject.activity.ProfileActivity"

And it working good:

public  class EasyCountDown extends AppCompatActivity {
    final Activity thisActivity = this;
    private Intent previousIntent,nextIntent;

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

        previousIntent = getIntent();
        String test = previousIntent.getStringExtra(MainActivity.TEST_TYPE);
        final String activity = test;
        Class newclass = null;

        try {
          newclass = Class.forName(activity);
        } catch (ClassNotFoundException c) {
            c.printStackTrace();
        }

        if(newclasss != null) {
            nextIntent = new Intent(thisActivity, newclass);
            startActivity(nextIntent);
        } else {
            Toast.makeText(getApplicationContext(),"new class null",Toast.LENGTH_SHORT).show();
        }
    }
} 

Dont forget you can use switch case or etc., because in this way you can get ClassNotFoundException and your intent will be null.

查看更多
Deceive 欺骗
3楼-- · 2019-07-28 11:50

The ComponentName object does just that:

String activity = intent.getStringExtra(MainActivity.TEST_TYPE);
Intent intent = new Intent(this, new ComponentName(this, activity));
startActivity(intent);

That's assuming this is an instance of Activity. (for a Fragment, use getActivity(), obv.)

查看更多
登录 后发表回答