开发者

Call other activities in an activity?

Say I have开发者_如何学JAVA 2 activities (ActivityOne and ActivityTwo). How would I call ActivityTwo from ActivityOne? Then how would I return to ActivityOne from ActivityTwo? For example, I have a listview with all the contacts on the host phone. When I tap on a contact, another activity shows information and allows editing of that contact. Then I could hit the back button, and I would go back to the exact state that ActivityOne was in before I called ActivityTwo. I was thinking an Intent object, but I am not sure. Could someone post some code?


In your first activity (AcitvityOne) you could call

Intent intent = new Intent(this, ActivityTwo.class);
startActivityForResult(intent, CODE);

Then you can override

public void onActivityResult(int reqCode, int resultCode, Intent data) {

to receive the result of this activity


In your example, it seems like you will want to pass data between Activity One and Activity Two (namely, the reference of the contact you want to edit), so you should use a Bundle with your intent in Activity One.

    Intent myIntent = new Intent(this, ActivityTwo.class);
    myIntent.putExtra("CONTACT", position);
    this.startActivity(myIntent);

"CONTACT" is a key and position is a value (position would have been defined before, it could be whatever you want it to be, for example an integer. The way you retrieve it is slightly different based on what type it is, note the getInt() in Activity Two code below).

And in Activity Two, in onCreate()

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        contact = extras.getInt("CONTACT");
        /**Do what you want with the integer value you have retrieved**/
    }

As for your other question, the back button removes the current Activity from the top of the tasks stack and therefore, you return to the previous Activity, normally in exactly the same state as you have left it.

However, if the phone is running low on memory, Android might kill off a process or Activity so it is possible in theory that your previous Activity will not show in exactly the same state as you have left it. If you have any important data, you should save it before launching Activity Two. If you just want to return to Activity One in the same state for user friendliness, then it's fine to rely on the back button.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜