我想知道,如果 fragment 或弹出窗口类与 Activity 分离,可以采用哪种方法将 fragment 或弹出窗口类生成的变量传输到 Activity 。
任何优雅方法的代码示例都值得赞赏。
最佳答案
这完全取决于您希望在 fragment 或弹出窗口到 Activity 之间传递哪种数据 一种方法是使用 Intent
//create an Intent object
Intent intent=new Intent(context, Activity.class);
//add data to the Intent object
intent.putExtra("text", "Data");
//start the second activity
startActivity(intent);
以及用于接收 Intent 数据的使用
getIntent().getStringExtra("text")
另一种方法是使用共享首选项
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
要读取偏好设置: String dateTimeKey = "com.example.app.datetime";
//使用 new Date() 使用默认值
long l = prefs.getLong(dateTimeKey, new Date().getTime());
编辑并保存首选项
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
关于java - 安卓 : Approach of passing variable generated in click event of fragment and popup window to activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348034/