我想根据之前活动的输入动态启动活动。我已经通过上一个活动输入了一个字符串,唯一的是这个特定的代码抛出了错误
无法解析构造函数' Intent(com.MentalMathWorkout.EasyCountDown,java.lang.String)'
有没有办法让这项工作?
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
}
答案 0 :(得分:4)
ComponentName对象就是这样:
String activity = intent.getStringExtra(MainActivity.TEST_TYPE);
Intent intent = new Intent(this, new ComponentName(this, activity));
startActivity(intent);
假设this
是Activity
的实例。 (对于Fragment
,请使用getActivity()
,obv。)
答案 1 :(得分:1)
我在这里上课:
com.yasinkacmaz.newproject.activity.ProfileActivity
我的测试字符串如下:
"com.yasinkacmaz.newproject.activity.ProfileActivity"
它运作良好:
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();
}
}
}
不要忘记你可以使用开关案例等,因为通过这种方式你可以得到ClassNotFoundException
,你的意图将是null
。