回答

1

这一切都取决于你想要的片段或弹出窗口之间传递到活动 一种方式是什么样的数据可以被使用意图

//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 prefs = this.getSharedPreferences(
     "com.example.app", Context.MODE_PRIVATE); 

要阅读完成rences: String dateTimeKey =“com.example.app.datetime”;

//使用默认值,使用新的Date()

long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

编辑和保存喜好

Date dt = getSomeDate(); 
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply(); 
1
  1. 在片段,创建一个接口(姑且称之为 VariableCallback为现在)使用一种返回类型void 的一种方法,该参数需要一个与变量相同的参数 generatin G。我们来调用方法onVariableGenerated
  2. 使活动托管碎片实现该接口。在VariableCallback类型的片段中创建 字段。我们称之为 callback
  3. 覆盖片段的onAttach(Context context) 方法,并将字段设置为指向上下文。确保您 将上下文投射到VariableCallback。现在
  4. ,当片段 产生的变量,你可以打电话 callback.onVariableGenerated(myVariable),以及将在 变量传递到承载片段的活性。
  5. 确保您 覆盖片段的onDetach()方法将callback 字段设置为空。这将防止活动的内存泄漏。
+0

那么情况如何,那么poupwindow或fragment需要活动中的信息? ((Activity)getActivity())。functionCall();在这里工作? – kilokahn

0

回答有点晚了,但有一个越多,你能做到这一点,我能想到的办法:本地广播

你可以使用一个LocalBroadcast经理和BroadcastListener活动中,从发送LocalBroadcast popupwindow:

在主要活动,你可以这样做:

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); 

将数据发送到活动中,你需要初始化LocalBroadcastManager实例,并火了广播 - 这可以通过一个按钮的OnClickListener被触发,或由PopupWindow的OnDismissListener

LocalBroadcastManager newLocalBroadcastManager = 
    LocalBroadcastManager.getInstance (getApplicationContext()); 
newLocalBroadcastManager.sendBroadcast (popupdataIntent); 
相关问题