意向回到旧活动后如何设置edittext值? [英] How to set edittext values after intent back to old activity?
问题描述
我正在使用Android.我在活动A中有一个按钮和EditText.当我单击该按钮时,它会以意图进入活动B.我在Acivity B中有一个ListView.单击列表项,然后将值存储在字符串中,然后再次使用意图返回到活动A.现在,我想在活动A的EditText字段中设置值.可以吗?
I am working with Android. I have a button and EditText in Activity A. When I click on the button it goes to Activity B with an Intent. I have a ListView in Acivity B. I clicked on list item and stored the values in string and again go back to Activity A with an Intent. Now I want to set the values in the EditText field in activity A. Is it possible????
推荐答案
您可以在Intent中的活动之间传递数据.这是在您的情况下构造代码的方式:
You can pass data between activities in Intents. Here's how you might structure the code in your case:
-
在ActivityA类中创建一个静态变量,该变量将用作请求代码:
Create a static variable in your ActivityA class, which will be used as request code:
public class ActivityA extends Activity {
//declare a static variable here, in your class
public static final int ACTIVITYB_REQUEST = 100;
活动A:单击按钮时,创建一个Intent并启动startActivityForResult()
Activity A: when button is clicked, create an Intent and startActivityForResult()
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, ACTIVITY_REQUEST);
在活动B中:单击某项时,将您的字符串存储在一个意图中,并调用setResult()和finish(),这将带您回到活动A:
In Activity B: when clicked an item, store your string in an intent and call setResult() and finish(), which will take you back to Activity 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();
在活动A:覆盖onActivityResult(),检查返回的数据并相应地设置您的EditText
In Activity A: override onActivityResult(), check for returned data and set your EditText accordingly
@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);
}
}
}
}
这篇关于意向回到旧活动后如何设置edittext值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!