Android最简单数据传递之携带集合

 利用Intent对象携带如ArrayList之类复杂些的数据

 这种原理是和利用Intent对象携带简单数据是一样的,只是要注意下。 在传参数前,要用新增加一个List将对象包起来。

 1,设置参数

  //传递复杂些的参数
        Map<String, Object> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);

        Intent intent = new Intent();
        intent.setClass(MainActivity.this,ComplexActivity.class);
        Bundle bundle = new Bundle();
        //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
        ArrayList bundlelist = new ArrayList();
        bundlelist.add(list);
        bundle.putParcelableArrayList("list",bundlelist);
        intent.putExtras(bundle);
        startActivity(intent);

2,接收参数

 this.setTitle("复杂参数传递例子");

    //接收参数
     Bundle bundle = getIntent().getExtras();
     ArrayList list = bundle.getParcelableArrayList("list");
    //从List中将参数转回 List<Map<String, Object>>
     List<Map<String, Object>> lists= (List<Map<String, Object>>)list.get(0);

     String sResult = "";
       for (Map<String, Object> m : lists) {
           for (String k : m.keySet()) {
               sResult += "\r\n" + k + " : " + m.get(k);
           }
       }

    TextView  tv = findViewById(R.id.tv);
    tv.setText(sResult);

猜你喜欢

转载自blog.csdn.net/weixin_42744183/article/details/89185151
今日推荐