Androidの循环之常用循环积累

其实在android的开发中体现了不少java的知识。

1.for循环的使用情景

在填充ListView上都是与适配器绑定的,我们看一下适配器的继承结构图。

详情参考Devin ZhangAndroid之Adapter用法总结这边文章。

用的比较多自然就属SimpleAdapter咯,使用简洁,可自定义界面。

看下这个适配器是如何填充的。

SimpleAdapter getAdapter(int[] res){//填充SimpleAdapter
        
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    
        for(int i=0;i<res.length;i++){//典型for循环
            Map<String,Object> map = new HashMap<String,Object> ();
            map.put("title", "标题"+i);
            map.put("context", "内容"+i);
            map.put("img", res[i]);
            list.add(map);
        }
        String[] from = new String[]{"title","context","img"};
        int[] to = new int[]{};
        SimpleAdapter adapter = new SimpleAdapter(this,list,android.R.layout.simple_list_item_1,from,to);
        return adapter;
    }

2.while循环的使用情景

在读取网络上的内容,不得不用到stream IO流。

void readNet(URL url){//读取网络
        
        try {
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine())!=null){//典型while循环
                sb.append(line);
            }
            Log.e("内容", sb.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

3.do while循环的使用情景

遍历游标通常的用法。

 void printCursor(Cursor cursor){//遍历游标
        
        if(cursor!=null&&cursor.moveToFirst()){
            
            do{//典型do while循环
                for(int i=0;i<cursor.getColumnCount();i++){
                    Log.e("第"+i+"列", cursor.getString(i));
                }
                
            }while(cursor.moveToNext());
            
        }
        
    }

 

 

 

原文地址:https://www.cnblogs.com/bvin/p/2690935.html