How should I communicate between activities? [duplicate]

大憨熊 提交于 2019-11-26 12:31:14

问题


I have 3 buttons. Button A, B, and C. Button A resides in Fragment. It starts intent (activity). Within the new activity button B and C reside. Button B says \"NEW\" while button C says \"OK\".

What I want to do is after clicking button B (\"NEW\") the intent should hold that button until the user hits button C (\"OK\") where the activity should destroy itself and go back to fragment where there is now a new button called (\"NEW\").

What are some easy ways to do this? And should I save this with sqlite if I want the app to remember the newly created button so that it\'s not lost upon onDestroy?

I\'m not very proficient within Android so hopefully someone can put it in laymans terms or point to an example.


回答1:


Use Bundle please read sth more about it. http://developer.android.com/reference/android/os/Bundle.html

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key);

This is the proper way to do that. Another way is SharedPreferences. http://developer.android.com/training/basics/data-storage/shared-preferences.html



来源:https://stackoverflow.com/questions/21393287/how-should-i-communicate-between-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!