Android : 将fragment和popup的点击事件中生成的变量window传递给activity的方法

Android : Approach of passing variable generated in click event of fragment and popup window to activity

我想知道有什么方法可以将片段或弹出窗口 window 的 class 生成的变量传输到 activity,前提是片段或弹出窗口 window class与activity分离。

感谢任何优雅方法的代码示例。

这完全取决于您希望在片段或弹出窗口 window 到 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);

并用于接收意向数据

getIntent().getStringExtra("text")

另一种方法可以使用 sharedpreferences

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

阅读首选项: 字符串 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();
  1. 在片段中,创建一个接口(我们称之为 VariableCallback 目前)使用 return 类型 void 的一种方法 它接受一个与您要使用的变量具有相同类型的参数 生成。让我们调用方法onVariableGenerated
  2. 使托管片段的 activity 实现该接口。创造 VariableCallback 类型片段中的字段。让我们称之为 callback
  3. 覆盖片段的 onAttach(Context context) 方法,并将字段设置为指向上下文。确保你 将上下文转换为 VariableCallback
  4. 现在,当片段 生成变量,你可以调用 callback.onVariableGenerated(myVariable),这将通过 承载该片段的 activity 的变量。
  5. 确保你 覆盖片段的 onDetach() 方法以设置 callback 字段为空。这将防止 activity.
  6. 的内存泄漏

回答有点晚了,但还有一种我能想到的方法:本地广播

您可以在 activity 中使用 LocalBroadcast Manager 和 BroadcastListener,并从弹出窗口发送 LocalBroadcast:

主要activity你可以这样做:

LocalBroadcastManager localBroadcastManager = 
    LocalBroadcastManager.getInstance (getApplicationContext ());

BroadcastReceiver popupdatareceiver = new BroadcastReceiver () {
    @Override
    public void onReceive(Context context, Intent intent) {
        ...
        // code to handle received data goes here
        }
    }
};

localBroadcastManager.registerReceiver (popupdatareceiver, new IntentFilter ("popupdata"));

您可以从 PopupWindow 发送本地广播,如下所示:

Intent popupdataIntent = new Intent ("popupdata");
Bundle popupdataBundle = new Bundle ();
...
// now add your data to the Bundle here
...
popupdataIntent.putExtra ("popupdata", popupdataBundle);

要将数据发送到 Activity,您需要初始化 LocalBroadcastManager 实例并触发广播 - 这可以由 Button 的 OnClickListener 或 PopupWindow 的 OnDismissListener 触发

LocalBroadcastManager newLocalBroadcastManager = 
     LocalBroadcastManager.getInstance (getApplicationContext ());
newLocalBroadcastManager.sendBroadcast (popupdataIntent);