dou*_*ter 0 android android-intent android-activity
我正在使用 Android。我在活动 A 中有一个按钮和 EditText。当我点击按钮时,它会带着一个 Intent 转到活动 B。我在活动 B 中有一个 ListView。我单击列表项并将值存储在字符串中,然后再次返回带有意图的活动 A。现在我想在活动 A 的 EditText 字段中设置值。这可能吗????
您可以在 Intent 中的活动之间传递数据。以下是您在案例中构建代码的方式:
在 ActivityA 类中创建一个静态变量,它将用作请求代码:
public class ActivityA extends Activity {
//declare a static variable here, in your class
public static final int ACTIVITYB_REQUEST = 100;
Run Code Online (Sandbox Code Playgroud)Activity A:当按钮被点击时,创建一个 Intent 和 startActivityForResult()
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, ACTIVITY_REQUEST);
Run Code Online (Sandbox Code Playgroud)在活动 B 中:当单击一个项目时,将您的字符串存储在一个意图中并调用 setResult() 和 finish(),这将带您回到活动 A:
//create an Intent
Intent resultIntent = new Intent();
//add your string from the clicked item
resultIntent.putExtra("string_key", clicked_item_string);
//return data back to parent, which is Activity A
setResult(RESULT_OK, resultIntent);
//finish current activity
finish();
Run Code Online (Sandbox Code Playgroud)在活动 A:覆盖 onActivityResult(),检查返回的数据并相应地设置您的 EditText
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//check if we are back from Activity B...
if (requestCode == ACTIVITYB_REQUEST) {
//and all went fine...
if (resultCode == RESULT_OK) {
//if Intent is not null
if (data != null) {
//get your string
String newString = data.getExtras().getString("string_key");
//set your EditText
someEditText.setText(newString);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)