转载自:http://blog.csdn.net/a1002450926/article/details/50341173
今天给大家带来XUtils3的基本介绍,本文章的案例都是基于XUtils3的API语法进行的演示。相信大家对这个框架也都了解过,下面简单介绍下XUtils3的一些基本知识。
XUtils3一共有4大功能:注解模块,网络模块,图片加载模块,数据库模块。使用XUtils只需要在libs文件夹里面加入一个jar包,如果对服务器返回的数据进行封装的话,还需要导入一个Gson的jar包。
Activity的注解
1.在Application的oncreate方法中加入下面代码: x.Ext.init(this);
2.在Activity的oncreate方法中加入下面代码: x.view().inject(this);
3.加载当前的Activity布局需要如下注解:
@ContentView加入到Activity的上方
4.给View进行初始化需要如下注解:
@InjectView
5.处理控件的各种响应事件需要如下注解:
@Envent
@ContentView(R.layout.activity_main)
public class MainActivity extends ActionBarActivity {
@ViewInject(R.id.btn_get)
Button btn_get;
@ViewInject(R.id.btn_post)
Button btn_post;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
x.view().inject(this);
btn_get.setText("发送get请求");
btn_post.setText("发送post请求");
}
//等同于@Event(value={R.id.btn_get,R.id.btn_post},type=View.OnClickListener.class)
@Event(value={R.id.btn_get,R.id.btn_post})
private void getEvent(View view){
switch(view.getId()){
case R.id.btn_get:
Toast.makeText(MainActivity.this, btn_get.getText().toString().trim(), 0).show();
break;
case R.id.btn_post:
Toast.makeText(MainActivity.this, btn_post.getText().toString().trim(), 0).show();
break;
}
}
Fragment的注解:
@ContentView(R.layout.fragment_first)
public class FirstFragment extends Fragment{
private MyAdapter adapter;
private List list=new ArrayList<>();
private List listUrl=new ArrayList<>();
private List listName=new ArrayList<>();
@ViewInject(R.id.btn_test)
Button btn_test;
@ViewInject(R.id.listView)
ListView listView;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return x.view().inject(this, inflater, container);
}
public class MyAdapter extends BaseAdapter{
private Context context;
private List list;
private LayoutInflater mInflater;
private ImageOptions options;
public ViewHolder holder;
public MyAdapter(Context context, List list) {
this.context = context;
this.list = list;
this.mInflater=LayoutInflater.from(context);
options=new ImageOptions.Builder().setLoadingDrawableId(R.drawable.ic_launcher)
.setLoadingDrawableId(R.drawable.ic_launcher).setUseMemCache(true).setCircular(true).build();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
holder=null;
if(convertView==null){
convertView=mInflater.inflate(R.layout.itemone, null);
holder=new ViewHolder();
x.view().inject(holder,convertView);
convertView.setTag(holder);
}
else{
holder=(ViewHolder) convertView.getTag();
}
Person bean=list.get(position);
holder.tv_name.setText(bean.getName());
x.image().bind(holder.iv_image, bean.getImgUrl(), options);
return convertView;
}
class ViewHolder{
@ViewInject(R.id.tv_name)
private TextView tv_name;
@ViewInject(R.id.iv_image)
private ImageView iv_image;
}
上面的代码是注解ViewHolder的标准模式,相信大家完全能够看明白。这里我加载图片使用到了XUtils3的加载网络图片的方法。后面我会详细进行讲解。
XUtils的网络请求方法和一些网络请求框架的用法非常类似,我进行了一些简单的封装。
封装一共有3个文件,分别是网络请求工具类XUtil,请求响应数据的解析类,还有一个就是一个请求成功的一个接口回调类。
代码如下:
public class XUtil {
/**
* 发送get请求
* @param
*/
public static Cancelable Get(String url,Map map,CommonCallback callback){
RequestParams params=new RequestParams(url);
if(null!=map){
for(Map.Entry entry : map.entrySet()){
params.addQueryStringParameter(entry.getKey(), entry.getValue());
}
}
Cancelable cancelable = x.http().get(params, callback);
return cancelable;
}
/**
* 发送post请求
* @param
*/
public static Cancelable Post(String url,Map map,CommonCallback callback){
RequestParams params=new RequestParams(url);
if(null!=map){
for(Map.Entry entry : map.entrySet()){
params.addParameter(entry.getKey(), entry.getValue());
}
}
Cancelable cancelable = x.http().post(params, callback);
return cancelable;
}
/**
* 上传文件
* @param
*/
public static Cancelable UpLoadFile(String url,Map map,CommonCallback callback){
RequestParams params=new RequestParams(url);
if(null!=map){
for(Map.Entry entry : map.entrySet()){
params.addParameter(entry.getKey(), entry.getValue());
}
}
params.setMultipart(true);
Cancelable cancelable = x.http().get(params, callback);
return cancelable;
}
/**
* 下载文件
* @param
*/
public static Cancelable DownLoadFile(String url,String filepath,CommonCallback callback){
RequestParams params=new RequestParams(url);
//设置断点续传
params.setAutoResume(true);
params.setSaveFilePath(filepath);
Cancelable cancelable = x.http().get(params, callback);
return cancelable;
}
}
public class JsonResponseParser implements ResponseParser {
//检查服务器返回的响应头信息
@Override
public void checkResponse(UriRequest request) throws Throwable {
}
/**
* 转换result为resultType类型的对象
*
* @param resultType 返回值类型(可能带有泛型信息)
* @param resultClass 返回值类型
* @param result 字符串数据
* @return
* @throws Throwable
*/
@Override
public Object parse(Type resultType, Class> resultClass, String result) throws Throwable {
return new Gson().fromJson(result, resultClass);
}
}
public class MyCallBack implements Callback.CommonCallback{
@Override
public void onSuccess(ResultType result) {
//可以根据公司的需求进行统一的请求成功的逻辑处理
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
//可以根据公司的需求进行统一的请求网络失败的逻辑处理
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
}
1.发送get请求示例:
//本get请求来自于免费测试接口:http://www.k780.com/api/entry.baidu
String url="http://api.k780.com:88/?app=idcard.get";
Map map=new HashMap<>();
map.put("appkey", "10003");
map.put("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
map.put("format", "json");
map.put("idcard", "110101199001011114");
XUtil.Get(url, map, new MyCallBack(){
@Override
public void onSuccess(PersonInfoBean result) {
super.onSuccess(result);
Log.e("result", result.toString());
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
}
});
2.发送post请求
String url="http://api.k780.com:88/?app=idcard.get";
Map map=new HashMap<>();
map.put("appkey", "10003");
map.put("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
map.put("format", "json");
map.put("idcard", "110101199001011114");
XUtil.Post(url, map, new MyCallBack(){
@Override
public void onSuccess(PersonInfoBean result) {
super.onSuccess(result);
Log.e("result", result.toString());
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
}
});
/**
* 上传文件(支持多文件上传)
*/
private void uploadfile() {
//图片上传地址
String url="";
Map map=new HashMap<>();
//传入自己的相应参数
//map.put(key, value);
//map.put(key, value);
XUtil.UpLoadFile(url, map, new MyCallBack(){
@Override
public void onSuccess(String result) {
super.onSuccess(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
}
});
}
private void downloadfile() {
//文件下载地址
String url="";
//文件保存在本地的路径
String filepath="";
XUtil.DownLoadFile(url, filepath,new MyCallBack(){
@Override
public void onSuccess(File result) {
super.onSuccess(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
}
});
private void downloadprogressfile() {
//文件下载地址
String url="";
//文件保存在本地的路径
String filepath="";
XUtil.DownLoadFile(url, filepath,new MyProgressCallBack(){
@Override
public void onSuccess(File result) {
super.onSuccess(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
}
@Override
public void onLoading(long total, long current,
boolean isDownloading) {
super.onLoading(total, current, isDownloading);
}
});
}
private void getxml() {
String url="http://flash.weather.com.cn/wmaps/xml/china.xml";
XUtil.Get(url, null, new MyCallBack(){
@Override
public void onSuccess(String xmlString) {
super.onSuccess(xmlString);
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlString));
int eventType = xmlPullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
String nodeName = xmlPullParser.getName();
if ("city".equals(nodeName)) {
String pName = xmlPullParser.getAttributeValue(0);
Log.e("TAG", "city is " + pName);
}
break;
}
eventType = xmlPullParser.next();
}
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
}
});
}
用法:
x.image().bind(imageView, url, imageOptions);
x.image().bind(imageView, "file:///sdcard/test.gif", imageOptions);
x.image().bind(imageView, "assets://test.gif", imageOptions);
x.image().bind(imageView, url, imageOptions, new Callback.CommonCallback() {...});
x.image().loadDrawable(url, imageOptions, new Callback.CommonCallback() {...});
x.image().loadFile(url, imageOptions, new Callback.CommonCallback() {...});
ImageOptions options=new ImageOptions.Builder()
//设置加载过程中的图片
.setLoadingDrawableId(R.drawable.ic_launcher)
//设置加载失败后的图片
.setFailureDrawableId(R.drawable.ic_launcher)
//设置使用缓存
.setUseMemCache(true)
//设置显示圆形图片
.setCircular(true)
//设置支持gif
.setIgnoreGif(false)
.build();
其余的一些配置请参考源码
如果需要对加载的图片进行操作的话,可以使用:
x.image().loadDrawable(url, imageOptions, new Callback.CommonCallback
通过返回的Drawable对象进行图片的处理,满足项目的个性化的要求.
说了这么多,我想大家至少会对XUtils3有了一个基本的了解,由于XUtils3的数据库的用法比较多,本篇文章不会去涉及,下一篇文章我会为大家详细讲解XUtils3的数据库模块。大家赶紧现在动手操作一下吧!本文涉及到的所有实例都会在下面的demo中有涉及到,请自行参考。
源码下载地址:http://download.csdn.net/detail/a1002450926/9364413