【问题标题】:Hashmap as param for a FragmentHashmap 作为片段的参数
【发布时间】:2015-11-19 00:10:18
【问题描述】:

我有一个带有 ExpandableList 的片段,其内容由 HashMap<String,List<String>> 提供。这个HashMap<String,List<String>>是在Fragment的Activity中填写的,我需要把它传递给fragment。

为此,我打算做一个片段交易,但我发现了问题:

fragment的newInstance方法中,给Bundle设置参数时,没有放HashMap的方法。

例如:

Bundle args = new Bundle();
args.putInt(ARG_PARAM1,index); //method .putHashmap doesn't exist.

那么,我如何将我的 hashmap 打包传递给 Fragment?请为此提供解决方案。在此先感谢

【问题讨论】:

  • Soo,你的 Activity 知道它正在显示的 Fragment 吗?你为什么不只是通过一个方法来传递它?或者您的活动实现了一个接口来检索该片段可以调用的地图。

标签: android android-fragments hashmap


【解决方案1】:

要传递 HashMap 这样做

MyFragment fr = new MyFragment(); // Replace with your Fragment class
Bundle bundle = new Bundle();
bundle.putSerializable("hashmap",mMap);
fr.setArguments(bundle);

要检索这样做

HashMap<String,List<String>> mMap = new HashMap<String,List<String>>();
Bundle b = this.getArguments();
if(b.getSerializable("hashmap") != null)
   mMap = (HashMap<String,List<String>>)b.getSerializable("hashmap");

【讨论】:

  • 警告未经检查的演员表
  • + uniqueNt 您可以放心地忽略此警告,因为您定义了自己的地图类型。 (将此行放在警告行上方:// noinspection unchecked
  • 很好的答案。谢谢。
【解决方案2】:

尝试使用:

Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, hereGoesYourHashMap);

根据文档:

https://developer.android.com/reference/java/util/HashMap.html

HashMapSerializable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多