Android intent传递hashMap对象,遍历hashMap,改变menu状态

来源:互联网 发布:动漫绘图软件 编辑:程序博客网 时间:2024/06/06 03:46

大家可以查看Intent可以传递的参数,有String,int,Boolean,Serializable等,就是不能直接传递HashMap时首先封装自己的HashMap对象:

[java] view plain copy
  1. public class SerializableHashMap implements Serializable {  
  2.    
  3.     private HashMap<String,Object> map;  
  4.    
  5.     public HashMap<String, Object> getMap() {  
  6.         return map;  
  7.     }  
  8.    
  9.     public void setMap(HashMap<String, Object> map) {  
  10.         this.map = map;  
  11.     }  
  12. }  

然后用Bundle传递封装的对象:

[java] view plain copy
  1. SerializableHashMap myMap=new SerializableHashMap();  
  2. myMap.setMap(map);//将hashmap数据添加到封装的myMap中  
  3. Bundle bundle=new Bundle();  
  4. bundle.putSerializable("map", myMap);  
  5. intent.putExtras(bundle);  


最后获取:

[java] view plain copy
  1. Bundle bundle = getIntent().getExtras();  
  2. SerializableHashMap serializableHashMap = (SerializableHashMap) bundle.get("map");  

HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的

第一种:

[java] view plain copy
  1. Map map = new HashMap();  
  2. Iterator iter = map.entrySet().iterator();  
  3. while (iter.hasNext()) {  
  4.     Map.Entry entry = (Map.Entry) iter.next();  
  5.     Object key = entry.getKey();  
  6.     Object val = entry.getValue();  
  7. }  

效率高,以后一定要使用此种方式!
第二种:
[java] view plain copy
  1. Map map = new HashMap();  
  2. Iterator iter = map.keySet().iterator();  
  3. while (iter.hasNext()) {  
  4.     Object key = iter.next();  
  5.     Object val = map.get(key);  
  6. }  


效率低,以后尽量少使用!

对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了


只被初始化一次(通常这么认为),则用下面的方法

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = this.getMenuInflater();

inflater.inflate(R.menu.menu, menu);

      menu.findItem(R.id.sort_by_name).setChecked(true);
}
我们不能将findViewById()用于menu ,因为他是menu,不是view. 我们可以更改menu的状态,只有它已经被创建或是被准备( created or prepared)好后才行。

0 0