Android_androidquery第三方库_Android-Query使用详解

Android之使用Android-query框架进行开发

      开发Android使用Android-query框架能够快速的,比传统开发android所要编写的代码要少得很多,容易阅读等优势。 

        下载文档及其例子和包的地址:http://code.google.com/p/android-query/

使用之前导入androidquery.jar包

1、基本使用:

<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span><span style="color:#ff0000;">// 必须实现AQuery这个类</span>
	AQuery aq = new AQuery(view);
	<span style="color:#ff0000;">// 按顺序分析:取得xml对应控件id,设置图片,设置可以显示,点击事件(方法someMethod必须是public修饰)</span>    

	aq.id(R.id.icon).image(R.drawable.icon).visible().clicked(this, "someMethod");  
	<span style="color:#ff0000;">// 设置文字内容</span>
        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();


2、AQuery也支持Fragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        
        View view = inflater.inflate(getContainerView(), container, false);             
                
        aq = new AQuery(getActivity(), view);
        return view;
    }   

3、使用AQuery异步加载图片

3.1 从网上读取图片

aq.id(R.id.image1).image(“图片URL”); 

3.2 缓存控制:  图片过大的话,避免记忆缓存

boolean memCache = false;

     boolean fileCache = true;

     aq.id(R.id.image1).image("http://www.vikispot.com/z/images/vikispot/android-w.png", memCache, fileCache);
3.3 当下载太多图片的时候需要降低图片采样率,第四个参数为了保证图片质量,一般范围时200-399
   aq.id(R.id.image1).image(imageUrl, true, true, 200, 0);
3.4 如果下载图片失败,处理的方法:1. 设置一个预定的图片  2. 使imageview不可见或者是gone
     aq.id(R.id.image1).image(imageUrl, true, true, 0, R.drawable.default_image);
     aq.id(R.id.image1).image(imageUrl, true, true, 0, AQuery.INVISIBLE);
     aq.id(R.id.image1).image(imageUrl, true, true, 0, AQuery.GONE);

3.5 图片预加载
    // 从之前的url取得小图片
     String thumbnail = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";   
     Bitmap preset = aq.getCachedImage(thumbnail);
    // 加载大图片前先显示小图片
     String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";            
    aq.id(R.id.image).image(imageUrl, false, false, 0, 0, preset, AQuery.FADE_IN);
3.6 在加载图片的时候显示进度条,progress里面传入id
    String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";            
     aq.id(R.id.image).progress(R.id.progress).image(imageUrl, false, false);
3.7 图片圆角显示,不支持大图片
     ImageOptions options = new ImageOptions();
     options.round = 15;
     aq.id(R.id.image).image(url, options);
3.8 图片长宽比例    
    // 保留原图片比例
    aq.id(R.id.image).image(imageUrl, true, true, 0, 0, null, AQuery.FADE_IN, AQuery.RATIO_PRESERVE);
    // 自定义图片比例
    //1:1, a square 
    aq.id(R.id.image2).image(imageUrl, true, true, 0, 0, null, 0, 1.0f / 1.0f);             
    aq.id(R.id.image3).image(imageUrl, true, true, 0, 0, null, 0, 1.5f / 1.0f);     
    //16:9, a video thumbnail
    aq.id(R.id.image4).image(imageUrl, true, true, 0, 0, null, 0, 9.0f / 16.0f);    
    aq.id(R.id.image5).image(imageUrl, true, true, 0, 0, null, 0, 3.0f / 4.0f);
3.9 图片描点,如果图片过高,描点可用来描述图片的哪一部分用于显示
    Anchor values:
·	1.0 : Display top of the image
	0 : Display the center of the image
	-1.0 : Display bottom of the image
	AQuery.ANCHOR_DYNAMIC : Display image with a top bias for photos.
=======================================================
	ImageOptions options = new ImageOptions();
	options.ratio = 1;
	options.anchor = 1.0;
	aq.id(R.id.image1).image(imageUrl, options);
3.10 自定义图片加载后的处理
    aq.id(R.id.image1).image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback(){});
3.11 异步从文件加载图片,建议使用降低采样率避免oom
    File file = new File(path);        
   //load image from file, down sample to target width of 300 pixels  
   aq.id(R.id.avatar).image(file, 300);
   //load image from file with callback
   aq.id(R.id.avatar).image(file, false, 300, new BitmapAjaxCallback(){
    @Override
    public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){
        iv.setImageBitmap(bm);
	}
});
3.12 如果之前image("url")已经成功,之后的都可以直接使用而不需要重新访问网络,也就是说之后可以离线访问此图像资源
3.13 文件中获取缓冲图片
     File file = aq.getCachedFile(url);
3.14 除了imageview,webview也可以用来放图片
     aq.id(R.id.web).progress(R.id.progress).webImage(url);
3.15 延迟图片加载,帮助你是否加载正在快速滚动的listview,详情参考文档使用
3.16 图片不使用缓存
     aq.id(R.id.image).image(url, false, false);
3.17 缓存配置,缓存一般是保存在内部文件系统,但也可以保存在SDCard里面
      File ext = Environment.getExternalStorageDirectory();
      File cacheDir = new File(ext, "myapp"); 
      AQUtility.setCacheDir(cacheDir);
3.18 共享图片,为了与其他程序共享图片,你需要把文件放在SDCard,makeSharedFile方法创建缓存地址的一个副本
      File file = aq.makeSharedFile(url, "android.png");
         if(file != null){
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                startActivityForResult(Intent.createChooser(intent, "Share via:"), SEND_REQUEST);
        }
3.19 配置,最好把配置写在application的onCreate方法,详细参考文档
3.20 程序退出时候需要把缓存清除
      if(isTaskRoot()){
	  AQUtility.cleanCacheAsync(this);
	}
      
      
或者: if(isTaskRoot()){
	//clean the file cache with advance option
        long triggerSize = 3000000; //大于3M时候开始清除
        long targetSize = 2000000;      //直到少于2M
        AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
        }
3.21 低内存处理
      public class MainApplication extends Application{
          @Override
         public void onLowMemory(){  
        //clear all memory cached images when system is in low memory
        //note that you can configure the max image cache count, see CONFIGURATION
         BitmapAjaxCallback.clearCache();
	}
}

4、异步网络

4.1. 添加权限:<uses-permission android:name="android.permission.INTERNET" />  

4.2. 支持的类型

JSONObject
JSONArray
String (HTML, XML)
XmlDom (XML parsing)
XmlPullParser (Large XML files)
byte array
User defined custom type (Transformer)

Bitmap 

4.3. 以Json数据为例,注意,红色部分是随你请求的数据类型一起改变

复制代码
String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
        
        aq.ajax(url,  JSONObject. classnew AjaxCallback< JSONObject>() {

                @Override
                 public  void callback(String url,  JSONObject json, AjaxStatus status) {
                        
                         if(json !=  null){
                                 // successful ajax call, show status code and json content
                                Toast.makeText(aq.getContext(), status.getCode() + ":" + json.toString(), Toast.LENGTH_LONG).show();
                        
                        } else{
                                 // ajax error, show error code
                                Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
                        }
                }

});  

复制代码

        

上面的形式也可以写成下面一样,他们是无条件对等 

复制代码
public  void asyncJson(){
        
         // perform a Google search in just a few lines of code
        
        String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";             
        aq.ajax(url,  JSONObject. classthis, "jsonCallback");
        
}

public  void jsonCallback(String url,  JSONObject json, AjaxStatus status){
        
         if(json !=  null){               
                 // successful ajax call          
        } else{          
                 // ajax error
        }
}         
复制代码


再举一个使用AQuery的XmlDom解析xml的例子,如果XML过大,使用XMLPullParser

复制代码
public  void xml_ajax(){         
        String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=8";              
        aq.ajax(url,  XmlDom. classthis, "picasaCb");           
}

public  void picasaCb(String url,  XmlDom xml, AjaxStatus status){
// 返回一系列为entry的结点,并把其add进list
        List<XmlDom> entries = xml.tags("entry");               
        List<String> titles =  new ArrayList<String>();
        
        String imageUrl =  null;
        
         for(XmlDom entry: entries){
                titles.add(entry.text("title")); //循环把第一个结点为title的文本放进title
                imageUrl = entry.tag("content", "type", "image/jpeg").attr("src");//把第一个结点为content,属性为type,属性值为image/jpeg的src属性值赋予给imageUri
        }
                
        aq.id(R.id.image).image(imageUrl);
}         
复制代码


4.4. 如果你想指定保存文件的位置,使用download方法

String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=16";             

File ext = Environment.getExternalStorageDirectory();
File target = new File(ext, "aquery/myfolder/photos.xml");              

aq.progress(R.id.progress).download(url, target, new AjaxCallback<File>(){
        
        public void callback(String url, File file, AjaxStatus status) {
                
                if(file != null){
                        showResult("File:" + file.length() + ":" + file, status);
                }else{
                        showResult("Failed", status);
                }
        }
   }); 

4.5. 自定义类型(文档例子是gson数据使用对象解析),详细见文档 

 

4.6. 使用Http Post (Multiple)

private void aync_multipart(){

        
        String url = "https://graph.facebook.com/me/photos";
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("message", "Message");
        
        //Simply put a byte[] to the params, AQuery will detect it and treat it as a multi-part post
        byte[] data = getImageData();
        params.put("source", data);
        
        //Alternatively, put a File or InputStream instead of byte[]
        //File file = getImageFile();           
        //params.put("source", file);
        
        AQuery aq = new AQuery(getApplicationContext());
        aq.auth(handle).ajax(url, params, JSONObject.class, this, "photoCb");
        
}
4.7. 使用ajax是很容易达到缓存的
     
     
String url = "http://www.google.com";

// 返回最近15分钟内的缓存副本,如果expire为-1,内容将会立即更新且缓存
long expire = 15 * 60 * 1000;

aq.ajax(url, String.class, expire, new AjaxCallback<String>() {

    @Override
    public void callback(String url, String html, AjaxStatus status) {        
        showResult(html);
    }
        
});
4.8. 使缓存无效
public void callback(String url, JSONObject json, AjaxStatus status) {
    
        if(json != null){
                if("1".equals(json.optString("status"))){
                        //do something
                }else{
                        // 不缓存
                        status.invalidate();
                }
        }
}
4.9. 同步调用: 如果ajax调用是在新开的线程,sync方法能够阻塞线程,直到ajax调用完毕,如果sync方法用在主线程将会引起Exception
String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
        
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();           
cb.url(url).type(JSONObject.class);             
        
aq.sync(cb);
        
JSONObject jo = cb.getResult();
AjaxStatus status = cb.getStatus();







根据项目名称就知道它的意思了,框架、实例、测试功能! AndroidQuery 一个轻量级的库,用于实现 Android 上的异步任务和操作 UI 元素。 项目含有26 个文件源文件,分析如下: auth含有: public class WebDialog extends Dialog 对话框显示网页信息 public class BasicHandle extends AccountHandle 本地帐号用户认证(Base64Coder编解码) public class FacebookHandle extends AccountHandle Facebook帐号用户认证(Base64Coder编解码) public class TwitterHandle extends AccountHandle Twitter帐号用户认证(Base64Coder编解码) public class GoogleHandle extends AccountHandle implements DialogInterface.OnClickListener, OnCancelListener Google帐号用户认证(Base64Coder编解码) public class LocationAjaxCallback extends AbstractAjaxCallback<Location, LocationAjaxCallback> //本地位置信息回调 封装了本地手机gps、network确认手机位置信息 然后返回最新位置信息 public abstract class AbstractAQuery<T extends AbstractAQuery<T>> implements Constants 模块类,含有AQuery所有方法。 主要方法如: public T find(int id) //查找根容器 public T parent(int id) //返回id容器的父容器 public T recycle(View root) //回收 public T id(int id) //返回id容器 public T auth(AccountHandle handle) //Ajax请求进行身份验证 public T transformer(Transformer transformer) //Ajax请求所需的对象类型转换 ……图片处理、下载、以及相关控件的方法操作! public class AQuery extends AbstractAQuery<AQuery> //主要类,实现上面的模版类 public abstract class AbstractAjaxCallback<T, K> implements Runnable //封装Ajax请求、回调 public class AjaxStatus //记录ajax请求的状态信息 如头信息、cookies 等 public class BitmapAjaxCallback extends AbstractAjaxCallback<Bitmap, BitmapAjaxCallback> //封装ajax请求图片 public class AQUtility //封装了特效方法 public class BitmapCache extends LinkedHashMap<String, Bitmap> //图片缓冲 使用哈希管理 public class Common implements Comparator<File>, Runnable, OnClickListener, OnLongClickListener, OnItemClickListener, OnScrollListener, OnItemSelectedListener, TextWatcher //仅供内部使用。一个共享的监听器类,以减少类的数量。 public class PredefinedBAOS extends ByteArrayOutputStream //管理缓冲流 返回流 public class Progress implements Runnable //进度条管理 public class RatioDrawable extends BitmapDrawable //图片 public class WebImage extends WebViewClient //web图片 public class XmlDom //XML解析
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值