请求网络数据后更新视图
请求网络数据后更新视图 
Android不能直接在子线程中更新视图,需要借助 Handler 类来实现视图更新
代码片段(1)
[代码] [Java]代码
| 01 | publicvoidonCreate(Bundle savedInstanceState) {   | 
| 02 |   super.onCreate(savedInstanceState);   | 
| 03 |   setContentView(R.layout.soft_recommend);   | 
| 04 |      | 
| 05 |   listview = (ListView) findViewById(R.id.recommSoftList);   | 
| 06 |   //判断数据对象是否为NULL  | 
| 07 |   if(SoftInfo.recommendSofts == null){   | 
| 08 |    //定义后台请求网络数据进度条  | 
| 09 |    recommProBar = (ProgressBar)findViewById(R.id.recommProBar4);   | 
| 10 |    recommProBar.setIndeterminate(false);   | 
| 11 |    recommProBar.setVisibility(View.VISIBLE);   | 
| 12 |    // 起始一个运行线程  | 
| 13 |    newThread(newRunnable() {   | 
| 14 |     publicvoidrun() {   | 
| 15 |      //请求网络数据   | 
| 16 |      iconTexts = SoftInfo.getRecommImageTexts(Constants.RECOMM_SOFT_URL);   | 
| 17 |      //执行视图更新   | 
| 18 |      SoftRecommend.this.listHandler   | 
| 19 |        .sendMessage(SoftRecommend.this.listHandler   | 
| 20 |          .obtainMessage());   | 
| 21 |     }   | 
| 22 |    }).start();    | 
| 23 |   }else{   | 
| 24 |    iconTexts = SoftInfo.getImageTexts(SoftInfo.recommendSofts);   | 
| 25 |    ImageTextAdapter adapter = newImageTextAdapter(this);   | 
| 26 |    adapter.setIconTexts(iconTexts);   | 
| 27 |    adapter.setViewId(R.layout.img_txt_view);   | 
| 28 |    listview.setAdapter(adapter);   | 
| 29 |   }   | 
| 30 | }  | 
| 31 | /**   | 
| 32 |   * 更新当前UI视图   | 
| 33 |   */ | 
| 34 |  Handler listHandler = newHandler(){   | 
| 35 |   /**   | 
| 36 |    *   | 
| 37 |    * @param msg   | 
| 38 |    * @author    | 
| 39 |    * @date 2010-12-7   | 
| 40 |    * (non-Javadoc)   | 
| 41 |    * @see android.os.Handler#handleMessage(android.os.Message)   | 
| 42 |    */ | 
| 43 |   publicvoidhandleMessage(Message msg){       | 
| 44 |    recommProBar.setVisibility(View.GONE);   | 
| 45 |      ImageTextAdapter adapter = newImageTextAdapter(SoftRecommend.this);   | 
| 46 |      adapter.setIconTexts(iconTexts);   | 
| 47 |      adapter.setViewId(R.layout.img_txt_view);   | 
| 48 |      listview.setAdapter(adapter);   | 
| 49 |      super.handleMessage(msg);   | 
| 50 |   }   | 
| 51 |  }; | 
 
                    
                 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号