简体   繁体   中英

Populate editText from a listView

I have an editText, next to it is a button. When you click the button, I use onClick to trigger an intent to start a new activity, that brings up the listView.

When you click an item in the listView, I want the listView activity to close and populate the editText with the item. It seems like I'm going at this all wrong, any suggestions?

You have to start the second activity "for result" and then set the result inside it. The result will then be passed to the first activity, where you can do with it whatever you want.

Check the reference for startActivityForResult here: http://developer.android.com/reference/android/app/Activity.html#startActivityForResult%28android.content.Intent,%20int%29

Use setResult in the second activity to set the result (integer only): http://developer.android.com/reference/android/app/Activity.html#setResult%28int%29

Use onActiviryResult to obtain the result: http://developer.android.com/reference/android/app/Activity.html#onActivityResult%28int,%20int,%20android.content.Intent%29

When you fire the intent, use "startActivityForResult", as described in Starting Activities, Getting Results .

When you fire the intent to the activity with the ListView, the line should look like this:

Intent someIntent = new Intent(someAction, someUri);
startActivityForResult(someIntent, SOME_REQUEST_CODE);    


Within the Activity with the ListView, before returning, use the "setResult" method to set the proper resultCode (the one that you passed in), and an Intent holding the data.

...
Intent data = new Intent();
data.putExtra("key",value);    
setResult(RESULT_OK, Intent data)
....


Then, back in your calling activity, onActivityResult will be called, containing that data.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == SOME_REQUEST_CODE) { //which activity you're returning from
       if (resultCode == RESULT_OK) { // Everything went as expected
            Bundle extras = data.getExtras();
            String val = extras.getString(key);
            doSomething(val)
            ...
       }
   }
}


Hope this helps!

What you'll want to do is start the new activity with StartActivityForResult() . Then have your onActivityResult() method receive the information selected in your selecting activity and set the EditText's text to the appropriate value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM