从主要活动向两个片段发送意图 [英] send intent from main activity to two fragment

查看:52
本文介绍了从主要活动向两个片段发送意图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个 Fragment ,我必须发送一些ID到 Fragment .我用这个:

I have 2 Fragment and I have to send some id to the Fragment. I use this:

public void onItemLongClick(View view, int position) {
    FragmentManager fm = getSupportFragmentManager();
    actionOption actionOption = new actionOption();
    actionOption.show(fm,"fragment_edit_name");
    ToDoModule movie = dbList.get(position);
    int y= movie.getId();
    Bundle args = new Bundle();
    args.putInt("exampleInt", y);
    actionOption.setArguments(args);

    EditOption editOption = new EditOption();

    ToDoModule bl = dbList.get(position);
    int z= movie.getId();
    Bundle zs = new Bundle();
    zs.putInt("int", y);
    editOption.setArguments(zs);
}

第一个 Fragment 正在工作,但第二个未发送.无法将值发送到 EditOption ?

First Fragment is working, but the second is not sent. Cannot send value to EditOption?

如何解决?

推荐答案

您尝试同时将一些数据传递到两个 Fragment 的情况非常不寻常.如果您能在问题中简短地写下您的处境,那将是很棒的.

Its very unusual that, you're trying to pass some data to two Fragment at the same time. It would be great if you could write the situation you have there in brief in your question.

无论如何,@ Prera​​kSola提出了一种解决方案,用于将要传递的数据保存在 SharedPreference 中,我认为它应该可以解决您的问题.

Anyway, @PrerakSola came up with a solution for saving the data you want to pass in a SharedPreference and I do think it should work in your case.

您正试图将影片ID传递给 actionOption 以及 editOption .您可能会尝试像这样先将ID存储在 SharedPreference 中.

You're trying to pass a movie id to actionOption as well as to editOption. You might try to store the id first in a SharedPreference like this.

来自您的活动

public void onItemLongClick(View view, int position) {

    // ... Your code 

    // Save the movie id
    SharedPreferences pref = getSharedPreferences("MY_APPLICATION", MODE_PRIVATE);
    pref.edit().putInt("MOVIE_ID", movie.getId()).commit();

    // Do not pass any bundle to the Fragment. Just transact the Fragment here
}

现在从您的 Fragment onCreateView 中从首选项中获取值.

Now from your Fragment's onCreateView fetch the value from preference.

SharedPreferences pref = getActivity().getSharedPreferences("MY_APPLICATION", MODE_PRIVATE);
String movieID = pref.getInt("MOVIE_ID", 0);

另一种方法是尝试使用 public static int 变量,该变量可能包含影片ID,并且可以从代码的任何位置访问它.

Another way you might try to have a public static int variable which might contain the movie id and you can access it from anywhere from your code.

希望有帮助!

这篇关于从主要活动向两个片段发送意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆