找不到一个好的答案。我有一个类(没有从主活动打开。 在那里,我想调用startActivityForResult,以了解何时在UI上执行某些操作。 如何正确操作?我将活动和上下文传递给了类。 上课:
private void init(){
Intent TestIntent = new Intent();
mActivity.startActivityForResult(TestIntent,MainActivity.TEST);
}
在主活动上:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
if (requestCode == TEST){
Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();
}
}
检查一下,您必须传递具有所需类意图的代码
private void init(){
Intent TestIntent = new Intent(this,SecondClass);
startActivityForResult(TestIntent,222);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
if (requestCode == 222){
Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();
}
}
您的TestIntent
为空。它没有任何内容可以告诉AndroidActivity
开始什么。您需要像这样创建Intent
:
private void init(){
Intent TestIntent = new Intent(mActivity, ActivityToStart.class);
mActivity.startActivityForResult(TestIntent,MainActivity.TEST);
}
private void init(){
Intent intent = new Intent(this,another.class);
startActivityForResult(intent,requestCode);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
if (requestCode == reruestCode){
Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();
}
}
private void getResponse(){
setResult(RESULT_OK,new Intent());
finish();
//Use this block of code in the second class.
}