Android Query使用教程

在android程序设计中,很多是要要实现异步任务,缓存,获取网络数据,提交请求等需求。Android Query是Github上非常好用的一个框架,简单高效的实现了以上功能,但Android Query的强大不止这些。

AQuery允许开发人员少写/做更多。更简单的代码更易于阅读和维护。

下面的代码完成了同样的工作,但是AQuery是工作变得简洁而优雅:

通常情况下:

public void renderContent(Content content, View view) {
        
        
        ImageView tbView = (ImageView) view.findViewById(R.id.icon); 
        if(tbView != null){
                
                tbView.setImageBitmap(R.drawable.icon);
                tbView.setVisibility(View.VISIBLE);
                
                tbView.setOnClickListener(new OnClickListener() {
                                
                                @Override
                                public void onClick(View v) {
                                        someMethod(v);
                                }
                        });
                
        }
        
        TextView nameView = (TextView) view.findViewById(R.id.name);    
        if(nameView != null){
                nameView.setText(content.getPname());
        }
        
        TextView timeView = (TextView) view.findViewById(R.id.time);  
        
        if(timeView != null){
                long now = System.currentTimeMillis();
                timeView.setText(FormatUtility.relativeTime(now, content.getCreate()));
                timeView.setVisibility(View.VISIBLE);
        }
        
        TextView descView = (TextView) view.findViewById(R.id.desc);    
        
        if(descView != null){
                descView.setText(content.getDesc());
                descView.setVisibility(View.VISIBLE);
        }
}

 使用AQuery:

public void renderContent(Content content, View view) {
        
        AQuery aq = new AQuery(view);
        
        aq.id(R.id.icon).image(R.drawable.icon).visible().clicked(this, "someMethod");  
        aq.id(R.id.name).text(content.getPname());
        aq.id(R.id.time).text(FormatUtility.relativeTime(System.currentTimeMillis(), content.getCreate())).visible();
        aq.id(R.id.desc).text(content.getDesc()).visible();             
        
        
}

 异步访问网络:

AQuery时访问网络和异步任务变得非常方便,代码如下:

public void asyncJson(){
        
        //ajax方法的第一参数是访问的URL,第二个参数是设置返回的类型,第四个参数是调用的回调方法
        
        String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";             
        aq.ajax(url, JSONObject.class, this, "jsonCallback");
        
}
//json就是返回的数据
public void jsonCallback(String url, JSONObject json, AjaxStatus status){
        
        if(json != null){               
                //successful ajax call          
        }else{          
                //ajax error
        }
        
}

猜你喜欢

转载自09572.iteye.com/blog/1621412