您的位置:首页 > 产品设计 > UI/UE

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

2014-08-22 22:57 309 查看
/article/1751689.html

/article/1751688.html

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

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

以下内容是我学习的一些心得分享:

第一节:

// 必须实现AQuery这个类

AQuery aq = new AQuery(view);

// 按顺序分析:取得xml对应控件id,设置图片,设置可以显示,点击事件(方法someMethod必须是public修饰)

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也支持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;

}

第二节: 使用AQuery异步加载图片

2.1 从网上读取图片

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

2.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);

2.3 当下载太多图片的时候需要降低图片采样率,第四个参数为了保证图片质量,一般范围时200-399
aq.id(R.id.image1).image(imageUrl, true, true, 200, 0);

2.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);

2.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);

2.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);

2.7 图片圆角显示,不支持大图片
ImageOptions options = new ImageOptions();
options.round = 15;
aq.id(R.id.image).image(url, options);

2.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);

2.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);

2.10 自定义图片加载后的处理
aq.id(R.id.image1).image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback(){});

2.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);
}
});

2.12 如果之前image("url")已经成功,之后的都可以直接使用而不需要重新访问网络,也就是说之后可以离线访问此图像资源

2.13 文件中获取缓冲图片
File file = aq.getCachedFile(url);

2.14 除了imageview,webview也可以用来放图片
aq.id(R.id.web).progress(R.id.progress).webImage(url);

2.15 延迟图片加载,帮助你是否加载正在快速滚动的listview,详情参考文档使用

2.16 图片不使用缓存
aq.id(R.id.image).image(url, false, false);

2.17 缓存配置,缓存一般是保存在内部文件系统,但也可以保存在SDCard里面
File ext = Environment.getExternalStorageDirectory();
File cacheDir = new File(ext, "myapp");
AQUtility.setCacheDir(cacheDir);

2.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);
}

2.19 配置,最好把配置写在application的onCreate方法,详细参考文档

2.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);
}
2.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();
}
}


异步网络:

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

2. 支持的类型
JSONObject

JSONArray

String (HTML, XML)

XmlDom (XML parsing)

XmlPullParser (Large XML files)

byte array

User defined custom type (Transformer)

Bitmap

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

String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";

aq.ajax(url, JSONObject.class, new 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.class, this, "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.class, this, "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. 如果你想指定保存文件的位置,使用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);
}
}
});


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

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");

}

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);
}

});
8. 使缓存无效
public void callback(String url, JSONObject json, AjaxStatus status) {

if(json != null){
if("1".equals(json.optString("status"))){
//do something
}else{
// 不缓存
status.invalidate();
}
}
}
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();


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

下面开认识一下该项目,项目如图:





根据项目名称就知道它的意思了,框架、实例、测试功能!

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解析

AndroidQuery 介绍完毕,那来看下是如何测试的。

public abstract class AbstractTest<T extends Activity> extends ActivityInstrumentationTestCase2<T> //初始化Activity、释放缓冲

关键方法如:

[html] view
plaincopy

protected void setUp() throws Exception { //

super.setUp();

aq = new AQuery(getActivity());

AQUtility.debug("new act", getActivity() + ":" + getActivity().isFinishing());

}

[html] view
plaincopy

<span style="white-space:pre"> </span>protected void clearCache(){ //清除缓冲

<span style="white-space:pre"> </span>

<span style="white-space:pre"> </span>BitmapAjaxCallback.clearCache();

<span style="white-space:pre"> </span>

<span style="white-space:pre"> </span>File cacheDir = AQUtility.getCacheDir(getActivity());

<span style="white-space:pre"> </span>AQUtility.cleanCache(cacheDir, 0, 0);

<span style="white-space:pre"> </span>

<span style="white-space:pre"> </span>waitSec(2000);

<span style="white-space:pre"> </span>}

public class AQueryAsyncTest extends AbstractTest<AQueryTestActivity> //测试同步ajax请求

主要方法:

[html] view
plaincopy

//Test: <K> T ajax(String url, Map<String, Object> params, Class<K> type, AjaxCallback<K> callback)

public void testAjaxPost(){ //测试ajax Post请求

String url = "http://search.twitter.com/search.json";

Map<String, String> params = new HashMap<String, String>();

params.put("q", "androidquery");

aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

@Override

public void callback(String url, JSONObject jo, AjaxStatus status) {

done(url, jo, status);

}

});

waitAsync();

JSONObject jo = (JSONObject) result;

assertNotNull(jo);

assertNotNull(jo.opt("results"));

}

[html] view
plaincopy

// Test: public <K> T ajax(String url, Class<K> type, long expire,

// AjaxCallback<K> callback)

public void testAjaxCache() { //ajax缓冲

String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";

AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {

@Override

public void callback(String url, JSONObject jo, AjaxStatus status) {

done(url, jo, status);

}

};

aq.ajax(url, JSONObject.class, 15 * 60 * 1000, cb);

waitAsync(2000);

JSONObject jo = (JSONObject) result;

assertNotNull(jo);

assertNotNull(jo.opt("responseData"));

File cached = aq.getCachedFile(url);

assertTrue(cached.exists());

assertTrue(cached.length() > 100);

}

[html] view
plaincopy

public void testAjaxLongBitmapURL() { //加载大图片

String dummy = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

String title = "Very long title " + dummy + dummy + dummy + dummy

+ dummy;

AQUtility.debug("title len", title.length());

String url = "https://chart.googleapis.com/chart?chid=1234&cht=lc&chtt="

+ title + "&chs=300x200&chxt=x&chd=t:40,20,50,20,100";

AjaxCallback<Bitmap> cb = new AjaxCallback<Bitmap>() {

@Override

public void callback(String url, Bitmap bm, AjaxStatus status) {

done(url, bm, status);

}

};

aq.ajax(url, Bitmap.class, 15 * 60 * 1000, cb);

waitAsync(2000);

assertNotNull(result);

File cached = aq.getCachedFile(url);

assertTrue(cached.exists());

assertTrue(cached.length() > 100);

}

[html] view
plaincopy

public void testAjaxPostMultiFile() throws IOException { //Post 多文件下载

String url = "http://www.androidquery.com/p/multipart";

Map<String, Object> params = new HashMap<String, Object>();

File tempFile1 = File.createTempFile("pre1", "bin");

File tempFile2 = File.createTempFile("pre2", "bin");

byte[] data1 = new byte[1234];

byte[] data2 = new byte[2345];

AQUtility.write(tempFile1, data1);

AQUtility.write(tempFile2, data2);

// byte[] data2 = new byte[2345];

// params.put("data", data);

// params.put("data2", data2);

params.put("data", tempFile1);

params.put("data2", tempFile2);

aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

@Override

public void callback(String url, JSONObject jo, AjaxStatus status) {

AQUtility.debug(status.getCode(), status.getError());

AQueryAsyncTest.this.result = jo;

}

});

waitAsync();

JSONObject jo = (JSONObject) result;

AQUtility.debug(jo);

assertNotNull(jo);

assertEquals(1234, jo.optInt("data"));

assertEquals(2345, jo.optInt("data2"));

}

……等等。

public class AQueryAuthTest extends AbstractTest<AQueryTestActivity> //测试身份认证

主要方法:

[html] view
plaincopy

public void testBasicAuthHandle() { //认证测试

BasicHandle handle = new BasicHandle("tinyeeliu@gmail.com", "password");

String url = "http://xpenser.com/api/v1.0/reports/";

aq.auth(handle).ajax(url, JSONArray.class, this, "basicCb");

waitAsync();

JSONArray jo = (JSONArray) result;

AQUtility.debug(jo);

assertNotNull(jo);

}

public class AQueryImageTest extends AbstractTest<AQueryTestActivity> //图片操作测试

主要方法:

[html] view
plaincopy

public void testImageBasicUrl() { //图片

clearCache();

AQUtility.post(new Runnable() {

@Override

public void run() {

aq.id(R.id.image).image(ICON_URL);

}

});

waitAsync(2000);

assertLoaded(aq.getImageView(), true);

Bitmap bm = aq.getCachedImage(ICON_URL);

assertNotNull(bm);

File file = aq.getCachedFile(ICON_URL);

assertNotNull(file);

}

[html] view
plaincopy

public void testImageNoCache() { //无缓存下载图片

clearCache();

AQUtility.post(new Runnable() {

@Override

public void run() {

aq.id(R.id.image).image(ICON_URL, false, false);

}

});

waitAsync(2000);

assertLoaded(aq.getImageView(), true);

Bitmap bm = aq.getCachedImage(ICON_URL);

assertNull(bm);

File file = aq.getCachedFile(ICON_URL);

assertNull(file);

}

[html] view
plaincopy

public void testImageFileWithCallback() { //

clearCache();

prefetchFile();

AQUtility.post(new Runnable() {

@Override

public void run() {

File file = aq.getCachedFile(LAND_URL);

aq.id(R.id.image2).image(file, true, 200,

new BitmapAjaxCallback() {

@Override

protected void callback(String url, ImageView iv,

Bitmap bm, AjaxStatus status) {

iv.setImageBitmap(bm);

assertNotNull(bm);

}

});

}

});

assertLoaded(aq.getImageView(), true);

}

public class AQueryLocationTest extends AbstractTest<AQueryTestActivity> //位置信息测试

[html] view
plaincopy

public void testLocationIter3Acc10000() {

LocationAjaxCallback cb = new LocationAjaxCallback() {

private int n;

@Override

public void callback(String url, Location loc, AjaxStatus status) {

n++;

AQUtility.debug(n);

AQUtility.debug(loc);

assertNotNull(loc);

if (n == 3) {

assertEquals("gps", loc.getProvider());

}

}

};

cb.timeout(30 * 1000).accuracy(10000).iteration(3).tolerance(-1);

cb.async(getActivity());

waitAsync(5000);

}

public void testLocationIter2Acc10000() { //位置测试

[html] view
plaincopy

<span style="white-space:pre"> </span>LocationAjaxCallback cb = new LocationAjaxCallback() {

private int n;

@Override

public void callback(String url, Location loc, AjaxStatus status) {

n++;

AQUtility.debug(n);

AQUtility.debug(loc);

assertNotNull(loc);

if (n == 2) {

assertEquals("gps", loc.getProvider());

}

}

};

cb.timeout(30 * 1000).accuracy(10000).iteration(2).tolerance(-1);

cb.async(getActivity());

waitAsync(5000);

}

public void testLocationIter1Acc10000() {

LocationAjaxCallback cb = new LocationAjaxCallback() {

private int n;

@Override

public void callback(String url, Location loc, AjaxStatus status) {

n++;

AQUtility.debug(n);

AQUtility.debug(loc);

assertNotNull(loc);

if (n == 1) {

assertEquals("gps", loc.getProvider());

}

}

};

cb.timeout(5 * 1000).accuracy(10000).iteration(1).tolerance(-1);

cb.async(getActivity());

waitAsync(5000);

}

public void testLocationIter2AccFail() {

LocationAjaxCallback cb = new LocationAjaxCallback() {

private int n;

@Override

public void callback(String url, Location loc, AjaxStatus status) {

n++;

AQUtility.debug(n);

AQUtility.debug(loc);

if (n == 2) {

assertNull(loc);

assertEquals(AjaxStatus.TRANSFORM_ERROR, status.getCode());

} else if (n < 2) {

assertNotNull(loc);

} else {

assertTrue(false);

}

}

};

cb.timeout(5 * 1000).accuracy(-1).iteration(2).tolerance(-1);

cb.async(getActivity());

waitAsync(6000);

}

public class AQueryMiscTest extends AbstractTest<AQueryTestActivity> //缓冲文件

[html] view
plaincopy

public void testTempFile() {

clearCache();

AQUtility.post(new Runnable() {

@Override

public void run() {

aq.id(R.id.image).image(ICON_URL);

}

});

waitAsync(2000);

assertNotNull(aq.getImageView().getDrawable());

File file = aq.getCachedFile(ICON_URL);

assertNotNull(file);

AQUtility.time("move");

File temp = aq.makeSharedFile(ICON_URL, "hello.png");

AQUtility.timeEnd("move", 0);

assertTrue(temp.exists());

assertTrue(temp.length() > 1000);

assertTrue(temp.getName().equals("hello.png"));

clearCache();

assertFalse(temp.exists());

File ghost = aq.getCachedFile("http://www.abc.com");

assertNull(ghost);

}

public class AQueryXmlTest extends AbstractTest<AQueryTestActivity> //测试解析xml

[html] view
plaincopy

public void testText2(){

assertEquals("https://picasaweb.google.com/data/feed/base/featured", xml.text("id"));

assertEquals("EricJamesPhoto_10.jpg", xml.child("entry").text("title"));

}

public void testAttr(){

assertEquals("application/atom+xml", xml.child("link").attr("type"));

}

public void testToString() throws SAXException{

InputStream is = this.getActivity().getResources().openRawResource(R.raw.colors);

xml = new XmlDom(is);

assertTrue(xml.toString().length() > 300);

}

public class IOUtility //测试打开网络文件

[html] view
plaincopy

public static byte[] openHttpResult(String urlPath, boolean retry) throws IOException{

AQUtility.debug("net", urlPath);

URL url = new URL(urlPath);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setUseCaches(false);

connection.setInstanceFollowRedirects(true);

connection.setConnectTimeout(NET_TIMEOUT);

int code = connection.getResponseCode();

if(code == 307 && retry){

String redirect = connection.getHeaderField("Location");

return openHttpResult(redirect, false);

}

if(code == -1 && retry){

return openHttpResult(urlPath, false);

}

AQUtility.debug("response", code);

if(code == -1 || code < 200 || code >= 300){

throw new IOException();

}

byte[] result = AQUtility.toBytes(connection.getInputStream());

return result;

}

public static String openString(String urlPath) throws IOException{

byte[] bytes = openBytes(urlPath);

return new String(bytes, "UTF-8");

}

看一下它的一个demo:

一:

[html] view
plaincopy

aq = new AQuery(this);

AjaxCallback.setReuseHttpClient(false);

// aq.id(R.id.text).text("point 1");

try {

/*

* String url =

* "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg"

* ;

*

* aq.id(new ImageView(this)).image(url, false, true, 200, 0, new

* BitmapAjaxCallback(){

*

* protected void callback(String url, ImageView iv, Bitmap bm,

* AjaxStatus status) { AQUtility.debug(bm.getWidth()); }

*

* });

*/

AQUtility.setDebug(true);

final ProgressDialog dialog = new ProgressDialog(this);

dialog.setIndeterminate(true);

dialog.setCancelable(true);

dialog.setInverseBackgroundForced(false);

dialog.setCanceledOnTouchOutside(true);

dialog.setTitle("Sending...");

Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

String url = "http://sssprog.ru";

final int num = number;

number++;

Log.d("sss", "loading started " + num);

aq.progress(dialog).ajax(url, String.class, new

AjaxCallback<String>() {

@Override

public void callback(String url, String html,

AjaxStatus status) {

Log.i("sss",

"ajax loaded " + num + " "

+ status.getCode() + " " + url);

Log.i("sss", "Res: " + html);

}

});

}

});

} catch (Exception e) {

e.printStackTrace();

}

二:

[html] view
plaincopy

//11-16 22:38:26.449: W/AQuery(18289): preset:http://graph.facebook.com/1281625122/picture

AQUtility.cleanCache(AQUtility.getCacheDir(this, AQuery.CACHE_DEFAULT), 0, 0);

BitmapAjaxCallback.clearCache();

String pic = "http://graph.facebook.com/1281625122/picture";

aq.id(R.id.image1).image(pic);

aq.id(R.id.image2).image(pic);

三:

[html] view
plaincopy

if(!init){

AQUtility.setDebug(true);

AQUtility.setCacheDir(null);

BitmapAjaxCallback.setPixelLimit(600 * 600);

BitmapAjaxCallback.setCacheLimit(100);

BitmapAjaxCallback.setMaxPixelLimit(5000000);

init = true;

ErrorReporter.installReporter(getApplicationContext());

}

super.onCreate(savedInstanceState);

type = getIntent().getStringExtra("type");

aq = new AQuery(this);

setContentView(R.layout.empty_list);

aq.id(android.R.id.list).adapter(getAA()).itemClicked(this, "itemClicked");

if(type == null && debug){

forward();

}

if(isTaskRoot()){

MarketService ms = new MarketService(this);

ms.level(MarketService.MINOR).checkVersion();

}

四:

[html] view
plaincopy

private void setupTest() { //初始化

AQUtility.setDebug(true);

aq = new AQuery(this);

aq.id(R.id.image1).text("Hihi");

aq.id(R.id.clicked1).clicked(this, "clicked1");

aq.id(R.id.clicked2).clicked(new OnClickListener() {

@Override

public void onClick(View v) {

TestUtility.showToast(ListenerTestActivity.this, "pass");

}

});

aq.id(R.id.image_reload).clicked(this, "reloadImage");

aq.id(R.id.image_clear_mem).clicked(this, "clearMem");

aq.id(R.id.image_clear_disk).clicked(this, "clearDisk");

aq.id(R.id.async_bytes).clicked(this, "asyncBytes");

aq.id(R.id.async_json).clicked(this, "asyncJson");

aq.id(R.id.async_bad_json).clicked(this, "asyncBadJson");

aq.id(R.id.async_bm).clicked(this, "asyncBitmap");

aq.id(R.id.async_html).clicked(this, "asyncHtml");

aq.id(R.id.async_post).clicked(this, "asyncPost");

loadImage();

}

public void asyncPost() {

// String url = "http://www.google.com/uds/GnewsSearch";

String url = "http://www.vikispot.com/api/likes";

Map<String, Object> params = new HashMap<String, Object>();

params.put("spotId", "1677246");

aq.ajax(url, params, JSONObject.class, this, "jsonCallback");

}

五:

[html] view
plaincopy

if(AQuery.SDK_INT >= 9 && TestUtility.isTestDevice(this)) { //初始化

AQUtility.debug("enable strict mode!");

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()

.detectAll()

.penaltyLog()

.build());

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()

.detectAll()

.penaltyLog()

//.penaltyDeath()

.build());

}

六:

[html] view
plaincopy

public static void flurryStart(Context context){

if(!isTestDevice(context)){

FlurryAgent.onStartSession(context, "D29A1QDKNZEIYFJBKXNR");

}

}

public static void flurryEvent(Context context, String name){

if(!isTestDevice(context)){

try{

FlurryAgent.onEvent(name, null);

}catch(Exception e){

e.printStackTrace();

}

}

}

public static void flurryStop(Context context){

if(!isTestDevice(context)){

FlurryAgent.onEndSession(context);

}

}

public static boolean isEmulator(){

return "sdk".equals(Build.PRODUCT);

}

private static String[] deviceIds = {"ffffffff-b588-0cd1-ffff-ffffb12a7939", "00000000-582e-8c83-ffff-ffffb12a7939", "ffffffff-a7af-71df-0033-c5870033c587", "00000000-2e56-36d7-ffff-ffffb12a7939", "ffffffff-b588-0cd1-ae81-42290033c587"};

private static Boolean testDevice;

public static boolean isTestDevice(Context context){

if(testDevice == null){

testDevice = isTestDevice(getDeviceId(context));

}

return testDevice;

}

private static boolean isTestDevice(String deviceId){

for(int i = 0; i < deviceIds.length; i++){

if(deviceIds[i].equals(deviceId)){

return true;

}

}

return false;

}

private static String deviceId;

public static String getDeviceId(Context context){

if(deviceId == null){

TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

String tmDevice, tmSerial, tmPhone, androidId;

tmDevice = "" + tm.getDeviceId();

tmSerial = "" + tm.getSimSerialNumber();

androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());

deviceId = deviceUuid.toString();

System.err.println(deviceId);

}

return deviceId;

}

七:

[html] view
plaincopy

public void auth_facebook() {//身份认证

FacebookHandle handle = new FacebookHandle(this, APP_ID, PERMISSIONS) {

@Override

public boolean expired(AbstractAjaxCallback<?, ?> cb,

AjaxStatus status) {

// custom check if re-authentication is required

if (status.getCode() == 401) {

return true;

}

return super.expired(cb, status);

}

};

String url = "https://graph.facebook.com/me/feed";

aq.auth(handle).progress(R.id.progress)

.ajax(url, JSONObject.class, this, "facebookCb");

}

[html] view
plaincopy

public void auth_twitter() { //身份认证

TwitterHandle handle = new TwitterHandle(this, CONSUMER_KEY,

CONSUMER_SECRET);

String url = "http://twitter.com/statuses/mentions.json";

aq.auth(handle).progress(R.id.progress)

.ajax(url, JSONArray.class, this, "twitterCb");

}

八:

[html] view
plaincopy

public void async_json() { //同步json分析

// AjaxCallback.setSSF(SSLSocketFactory.getSocketFactory());

String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";

AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {

@Override

public void callback(String url, JSONObject json, AjaxStatus status) {

showResult(json, status);

}

};

cb.url(url).type(JSONObject.class);

aq.progress(R.id.progress).ajax(cb);

}

public void async_html() { //同步html分析

String url = "http://www.google.com";

aq.progress(R.id.progress).ajax(url, String.class,

new AjaxCallback<String>() {

@Override

public void callback(String url, String html,

AjaxStatus status) {

showResult(html, status);

}

});

}

public void async_bytes() {

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.progress(R.id.progress).ajax(url, byte[].class,

new AjaxCallback<byte[]>() {

@Override

public void callback(String url, byte[] object,

AjaxStatus status) {

showResult("bytes array length:" + object.length,

status);

}

});

}

public void async_xml() {

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

aq.progress(R.id.progress).ajax(url, XmlDom.class,

new AjaxCallback<XmlDom>() {

public void callback(String url, XmlDom xml,

AjaxStatus status) {

showResult(xml, status);

}

});

}

public void async_file() {

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

aq.progress(R.id.progress).ajax(url, File.class,

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);

}

}

});

}

public void async_file_custom() {

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

File ext = Environment.getExternalStorageDirectory();

File target = new File(ext, "aquery/myfolder2/photos1.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);

}

}

});

}

public void async_web() {

String MOBILE_AGENT = "Mozilla/5.0 (Linux; U; Android 2.2) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533";

AjaxCallback.setAgent(MOBILE_AGENT);

aq.id(R.id.result).gone();

aq.id(R.id.web).visible();

// String url =

// "http://www.shouda8.com/shouda/tunshixingkong/14/2618.htm";

// String url =

// "http://www.engadget.com/2012/05/04/samsung-releases-galaxy-tab-2-7-and-10-source-code";

String url = "http://mashable.com/2012/05/05/new-york-city-tech-startups/";

// wv.loadUrl("file:///android_asset/html_no_copy/demo_welcome.html");

long expire = 3600000;

aq.progress(R.id.progress).ajax(url, String.class, expire,

new AjaxCallback<String>() {

@Override

public void callback(String url, String html,

AjaxStatus status) {

AQUtility.debug("file length:" + html.length());

showResult("", status);

WebView wv = aq.id(R.id.web).getWebView();

WebSettings ws = wv.getSettings();

// ws.setJavaScriptEnabled(true);

wv.loadDataWithBaseURL(url, html, "text/html", "utf-8",

null);

// wv.loadUrl(url);

// showResult(html, status);

}

});

}

public void async_inputstream() {

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

aq.progress(R.id.progress).ajax(url, InputStream.class,

new AjaxCallback<InputStream>() {

public void callback(String url, InputStream is,

AjaxStatus status) {

if (is != null) {

showResult("InputStream:" + is, status);

} else {

showResult("Failed", status);

}

}

});

}

public void async_xpp() {

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

aq.progress(R.id.progress).ajax(url, XmlPullParser.class,

new AjaxCallback<XmlPullParser>() {

public void callback(String url, XmlPullParser xpp,

AjaxStatus status) {

Map<String, String> images = new LinkedHashMap<String, String>();

String currentTitle = null;

try {

int eventType = xpp.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {

if (eventType == XmlPullParser.START_TAG) {

String tag = xpp.getName();

if ("title".equals(tag)) {

currentTitle = xpp.nextText();

} else if ("content".equals(tag)) {

String imageUrl = xpp

.getAttributeValue(0);

images.put(currentTitle, imageUrl);

}

}

eventType = xpp.next();

}

} catch (Exception e) {

AQUtility.report(e);

}

showResult(images, status);

}

});

}

public void async_json_array() {

String url = "http://androidquery.appspot.com/test/jsonarray.json";

aq.progress(R.id.progress).ajax(url, JSONArray.class,

new AjaxCallback<JSONArray>() {

public void callback(String url, JSONArray ja,

AjaxStatus status) {

showResult(ja, status);

}

});

}

九:

[html] view
plaincopy

public void location_ajax() { /ajax请求位子信息

aq.id(R.id.result).text("");

LocationAjaxCallback cb = new LocationAjaxCallback();

cb.weakHandler(this, "locationCb").timeout(30 * 1000).accuracy(1000)

.iteration(3);

cb.async(this);

this.cb = cb;

}

public void locationCb(String url, Location loc, AjaxStatus status) {

if (loc != null) {

appendResult(loc);

}

}

十:

[html] view
plaincopy

public void xml_ajax() { //分析 ajax请求xml

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

aq.progress(R.id.progress).ajax(url, XmlDom.class, this, "picasaCb");

}

public void picasaCb(String url, XmlDom xml, AjaxStatus status) {

showResult(xml, status);

if (xml == null)

return;

List<XmlDom> entries = xml.tags("entry");

List<String> titles = new ArrayList<String>();

String imageUrl = null;

for (XmlDom entry : entries) {

titles.add(entry.text("title"));

imageUrl = entry.tag("content", "type", "image/jpeg").attr("src");

}

showTextResult(titles);

aq.id(R.id.image).image(imageUrl);

}

十一:

[html] view
plaincopy

private void image_zoom(){ //图片放大

String url = "http://farm4.static.flickr.com/3531/3769416703_b76406f9de.jpg";

aq.id(R.id.text).text("Try pinch zoom with finger.");

aq.id(R.id.web).progress(R.id.progress).webImage(url);

//aq.id(R.id.web).progress(R.id.progress).webImage(url, true, true, 0xFF000000);

}

十二:

[html] view
plaincopy

public void renderNews(String url, JSONObject json, AjaxStatus status) { //渲染

if(json == null) return;

JSONArray ja = json.optJSONObject("responseData").optJSONArray("results");

if(ja == null) return;

List<JSONObject> items = new ArrayList<JSONObject>();

addItems(ja, items);

addItems(ja, items);

addItems(ja, items);

addItems(ja, items);

listAq = new AQuery(this);

ArrayAdapter<JSONObject> aa = new ArrayAdapter<JSONObject>(this, R.layout.content_item_s, items){

@Override

public View getView(int position, View convertView, ViewGroup parent) {

if(convertView == null){

convertView = getLayoutInflater().inflate(R.layout.content_item_s, null);

}

JSONObject jo = getItem(position);

AQuery aq = listAq.recycle(convertView);

aq.id(R.id.name).text(jo.optString("titleNoFormatting", "No Title"));

aq.id(R.id.meta).text(jo.optString("publisher", ""));

String tb = jo.optJSONObject("image").optString("tbUrl");

aq.id(R.id.tb).progress(R.id.progress).image(tb, true, true, 0, 0, null, AQuery.FADE_IN_NETWORK, 1.0f);

return convertView;

}

};

aq.id(R.id.list).adapter(aa);

}

十三:

[html] view
plaincopy

public void image_simple(){

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.id(R.id.image).progress(R.id.progress).image(url);

}

public void image_cache(){

boolean memCache = false;

boolean fileCache = true;

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.id(R.id.image).progress(R.id.progress).image(url, memCache, fileCache);

}

public void image_down(){

String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";

aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 200, 0);

}

public void image_fallback(){

String imageUrl = "http://www.vikispot.com/z/images/vikispot/xyz.png";

aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, R.drawable.image_missing);

}

public void image_preload(){

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).progress(R.id.progress).image(imageUrl, false, false, 0, 0, preset, 0, AQuery.RATIO_PRESERVE);

}

public void image_progress(){

ProgressDialog dialog = new ProgressDialog(this);

dialog.setIndeterminate(true);

dialog.setCancelable(true);

dialog.setInverseBackgroundForced(false);

dialog.setCanceledOnTouchOutside(true);

dialog.setTitle("Sending...");

aq.id(R.id.image).clear();

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);

//imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

//aq.id(R.id.image).progress(dialog).image(imageUrl, true, true);

}

public void image_animation(){

String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, 0, null, AQuery.FADE_IN);

}

public void image_animation2(){

String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, 0, null, R.anim.slide_in_left);

}

public void image_ratio(){

String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";

aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, 0, null, AQuery.FADE_IN, AQuery.RATIO_PRESERVE);

}

public void image_round(){

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.id(R.id.image);//.progress(R.id.progress).image(url);

BitmapAjaxCallback.async(this, this, aq.getImageView(), url, true, true, 0, 0, null, 0, 0, 0, null, null, 0, 15);

}

public void image_file(){

String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";

File file = aq.getCachedFile(imageUrl);

if(file != null){

aq.id(R.id.image).progress(R.id.progress).image(file, 300);

}

}

public void image_custom(){

String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

final int tint = 0x77AA0000;

aq.id(R.id.image).progress(R.id.progress).visible().image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback(){

@Override

public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){

iv.setBackgroundColor(0xffcc0000);

iv.setImageBitmap(bm);

//iv.setColorFilter(tint, PorterDuff.Mode.SRC_ATOP);

showMeta(status);

}

}.round(10));

}

public void image_file_custom(){

String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";

File file = aq.getCachedFile(imageUrl);

final int tint = 0x77AA0000;

if(file != null){

aq.id(R.id.image).progress(R.id.progress).visible().image(file, true, 300, new BitmapAjaxCallback(){

@Override

public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){

iv.setImageBitmap(bm);

iv.setColorFilter(tint, PorterDuff.Mode.SRC_ATOP);

showMeta(status);

}

});

}

}

public void image_dup(){

String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.id(R.id.image).image(imageUrl, false, false);

//no network fetch for 2nd request, image will be shown when first request is completed

aq.id(R.id.image2).image(imageUrl, false, false);

}

public void image_button(){

String tb = "http://androidquery.appspot.com/z/demo/button.png";

aq.id(R.id.button).image(tb);

}

public void image_advance(){

aq.id(R.id.image).width(LayoutParams.FILL_PARENT);

String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";

BitmapAjaxCallback cb = new BitmapAjaxCallback();

cb.url(imageUrl).animation(AQuery.FADE_IN).ratio(1.0f);

aq.id(R.id.image).image(cb);

}

public void image_access_file(){ //

String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

File file = aq.getCachedFile(imageUrl);

if(file != null){

showResult("File:" + file + " Length:" + file.length(), null);

}

}

public void image_access_memory(){ //

String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";

Bitmap bm = aq.getCachedImage(imageUrl);

if(bm != null){

showResult("Dimension:" + bm.getWidth() + "x" + bm.getHeight(), null);

}

}

public void image_pre_cache(){

String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";

File file = aq.getCachedFile(imageUrl);

if(file != null){

showTextResult("File cached:" + file.getAbsolutePath() + " Length:" + file.length());

}

aq.id(R.id.image).image(imageUrl);

}

public void image_nocache(){ //无缓存图片

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

//force a network refetch without any caching

aq.id(R.id.image).image(url, false, false);

//force no proxy cache by appending a random number

String url2 = url + "?t=" + System.currentTimeMillis();

aq.id(R.id.image2).image(url2, false, false);

}

public void image_clear_mem(){ //清除内存图片

BitmapAjaxCallback.clearCache();

showTextResult("Bitmap Memcache cleared");

}

public void image_clear_disk(){ //清除图片目录

AQUtility.cleanCacheAsync(this, 0, 0);

showTextResult("File cache cleared");

}

public void image_cache_dir(){ //缓存目录

File ext = Environment.getExternalStorageDirectory();

File cacheDir = new File(ext, "myapp");

AQUtility.setCacheDir(cacheDir);

AQUtility.debug("cache dir exist", cacheDir.exists());

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

aq.cache(url, 0);

File file = AQUtility.getCacheFile(AQUtility.getCacheDir(this, AQuery.CACHE_DEFAULT), url);

showTextResult(file.getAbsolutePath());

}

private static final int SEND_REQUEST = 12;

public void image_send(){ //图片发送

String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

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);

}

}

public void image_chart(){ //图片

// EXAMPLE from http://code.google.com/p/charts4j/
final int NUM_POINTS = 25;

final double[] competition = new double[NUM_POINTS];

final double[] mywebsite = new double[NUM_POINTS];

for (int i = 0; i < NUM_POINTS; i++) {

competition[i] = 100-(Math.cos(30*i*Math.PI/180)*10 + 50)*i/20;

mywebsite[i] = (Math.cos(30*i*Math.PI/180)*10 + 50)*i/20;

}

Line line1 = Plots.newLine(Data.newData(mywebsite), Color.newColor("CA3D05"), "My Website.com");

line1.setLineStyle(LineStyle.newLineStyle(3, 1, 0));

line1.addShapeMarkers(Shape.DIAMOND, Color.newColor("CA3D05"), 12);

line1.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);

Line line2 = Plots.newLine(Data.newData(competition), SKYBLUE, "Competition.com");

line2.setLineStyle(LineStyle.newLineStyle(3, 1, 0));

line2.addShapeMarkers(Shape.DIAMOND, SKYBLUE, 12);

line2.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);

// Defining chart.

LineChart chart = GCharts.newLineChart(line1, line2);

chart.setSize(600, 450);

String dummy = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

String title = "Very long title " + dummy + dummy + dummy + dummy + dummy;

chart.setTitle(title);

chart.addHorizontalRangeMarker(40, 60, Color.newColor(RED, 30));

chart.addVerticalRangeMarker(70, 90, Color.newColor(GREEN, 30));

chart.setGrid(25, 25, 3, 2);

// Defining axis info and styles

AxisStyle axisStyle = AxisStyle.newAxisStyle(WHITE, 12, AxisTextAlignment.CENTER);

AxisLabels xAxis = AxisLabelsFactory.newAxisLabels("Nov", "Dec", "Jan", "Feb", "Mar");

xAxis.setAxisStyle(axisStyle);

AxisLabels xAxis2 = AxisLabelsFactory.newAxisLabels("2007", "2007", "2008", "2008", "2008");

xAxis2.setAxisStyle(axisStyle);

AxisLabels yAxis = AxisLabelsFactory.newAxisLabels("", "25", "50", "75", "100");

AxisLabels xAxis3 = AxisLabelsFactory.newAxisLabels("Month", 50.0);

xAxis3.setAxisStyle(AxisStyle.newAxisStyle(WHITE, 14, AxisTextAlignment.CENTER));

yAxis.setAxisStyle(axisStyle);

AxisLabels yAxis2 = AxisLabelsFactory.newAxisLabels("Hits", 50.0);

yAxis2.setAxisStyle(AxisStyle.newAxisStyle(WHITE, 14, AxisTextAlignment.CENTER));

yAxis2.setAxisStyle(axisStyle);

// Adding axis info to chart.

chart.addXAxisLabels(xAxis);

chart.addXAxisLabels(xAxis2);

chart.addXAxisLabels(xAxis3);

chart.addYAxisLabels(yAxis);

chart.addYAxisLabels(yAxis2);

// Defining background and chart fills.

chart.setBackgroundFill(Fills.newSolidFill(Color.newColor("1F1D1D")));

LinearGradientFill fill = Fills.newLinearGradientFill(0, Color.newColor("363433"), 100);

fill.addColorAndOffset(Color.newColor("2E2B2A"), 0);

chart.setAreaFill(fill);

String url = chart.toURLString();

showTextResult("Image URL:" + url);

aq.id(R.id.image).progress(R.id.progress).image(url);

}

十四:

[html] view
plaincopy

public void aspectRatio() { //图片效果比率

String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";

aq.id(R.id.image1)

.progress(R.id.progress)

.image(imageUrl, true, true, 0, 0, null, 0,

AQuery.RATIO_PRESERVE);

// aq.id(R.id.image1).progress(R.id.progress).image("http://www.google.com/a.jpg",

// true, true, 0, AQuery.GONE, null, 0, AQuery.RATIO_PRESERVE);

aq.id(R.id.text1).text("Original Aspect Ratio");

aq.id(R.id.image2).image(imageUrl, true, true, 0, 0, null, 0,

1.0f / 1.0f);

aq.id(R.id.text2).text("1:1");

aq.id(R.id.image3).image(imageUrl, true, true, 0, 0, null, 0,

1.5f / 1.0f);

aq.id(R.id.text3).text("1.5:1");

aq.id(R.id.image4).image(imageUrl, true, true, 0, 0, null, 0,

9.0f / 16.0f);

aq.id(R.id.text4).text("9:16");

aq.id(R.id.image5).image(imageUrl, true, true, 0, 0, null, 0,

3.0f / 4.0f);

aq.id(R.id.text5).text("3:4");

}

学习的目标是成熟!

项目下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: