android 高级之旅 (二 )xUtils3 基本用法

xutils功能主要有4部分:注解、网络加载、图片加载、数据库;其他的还有log输出、MD5加密等小功能

总之,xutils3是一款功能强大的框架,更多特性以及简介 移步:点击这里 


一、xUtils可以直接从androidstudio中导入依赖,导入成功后需添加权限如下:

  


二、xutils需要在application中的oncreate方法中初始化,

在activity中:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true);
    }
}
在fragment中:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        injected = true;
        View view = x.view().inject(this, inflater, container);
        return view;
    }

四大功能:

一、注解    ViewUtils模块:

与很多注解框架用法大同小异(如greendao)

 @ViewInject(R.id.image1)
    private ImageView image1;
@Event(value = R.id.t1)
    private void onBtn1ClickListener(View view) { ... }
需要注意的是,在给控件添加点击事件等监听时,监听方法的修饰符必须为私有(private)

支持同时绑定多个控件id,以数组方式写入注解

@Event(value = {R.id.t1,R.id.t2,R.id.t3})
    private void onBtn1ClickListener(View view) { ... }

//在Fragment中注入:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.bitmap_fragment, container, false); // 加载fragment布局
    ViewUtils.inject(this, view); //注入view和事件
    ...
}
//在PreferenceFragment中注入:
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ViewUtils.inject(this, getPreferenceScreen()); //注入view和事件
    ...
}

二、加载图片  BitmapUtils模块

图片加载使用非常简单,只有几个非常容易理解的API,可以很轻松的实现对 图片的载入动画、 图片的缩放、旋转、圆角、圆形等处理,

 @Event(value = R.id.t1)
    private void onBtn1ClickListener(View view) {
        //自定义的缩放动画
        ScaleAnimation scaleAnimation = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.1f, Animation.RELATIVE_TO_SELF, 0.3f);
        scaleAnimation.setDuration(3000);
        
        ImageOptions imageOptions = new ImageOptions.Builder()
                .setCircular(true) //是否为圆形
                .setAnimation(scaleAnimation) //动画
                .setSize(1000, 1500)// 设置尺寸
                .setRadius(50)  //设置圆角
                .setAutoRotate(true) //自动旋转
                .build();
        x.image().bind(image1, imageUrl,imageOptions, new Callback.CacheCallback() {
            @Override
            public boolean onCache(Drawable result) {
                return false;
            }
            @Override
            public void onSuccess(Drawable result) {
                image1.setImageDrawable(result);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }


三、数据库  DbUtils模块

DbUtils db = DbUtils.create(this);
User user = new User(); //这里需要注意的是User对象必须有id属性,或者有通过@ID注解的属性
user.setEmail("[email protected]");
user.setName("wyouflf");
db.save(user); // 使用saveBindingId保存实体时会为实体的id赋值

...
// 查找
Parent entity = db.findById(Parent.class, parent.getId());
List list = db.findAll(Parent.class);//通过类型查找

Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=","test"));

// IS NULL
Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=", null));
// IS NOT NULL
Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","!=", null));

// WHERE id<54 AND (age>20 OR age<30) ORDER BY id LIMIT pageSize OFFSET pageOffset
List list = db.findAll(Selector.from(Parent.class)
                                   .where("id" ,"<", 54)
                                   .and(WhereBuilder.b("age", ">", 20).or("age", " < ", 30))
                                   .orderBy("id")
                                   .limit(pageSize)
                                   .offset(pageSize * pageIndex));

// op为"in"时,最后一个参数必须是数组或Iterable的实现类(例如List等)
Parent test = db.findFirst(Selector.from(Parent.class).where("id", "in", new int[]{1, 2, 3}));
// op为"between"时,最后一个参数必须是数组或Iterable的实现类(例如List等)
Parent test = db.findFirst(Selector.from(Parent.class).where("id", "between", new String[]{"1", "5"}));

DbModel dbModel = db.findDbModelAll(Selector.from(Parent.class).select("name"));//select("name")只取出name列
List dbModels = db.findDbModelAll(Selector.from(Parent.class).groupBy("name").select("name", "count(name)"));
...

List dbModels = db.findDbModelAll(sql); // 自定义sql查询
db.execNonQuery(sql) // 执行自定义sql
...

四、网络请求HttpUtils模块

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    @ViewInject(R.id.btn_get)
    private Button btnGet;

    @ViewInject(R.id.tv_test)
    private TextView tvTest;

    private static  final String jsonPath = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&devid=866500021200250&appname=QQHouse&mod=appkft&reqnum=&pageflag=&act=newslist&channel=71&buttonmore=&cityid=1";
    public final static  String pathPost = "http://mrobot.pcauto.com.cn/v2/cms/channels/1?";


    private Callback.Cancelable cancelable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }

    //网路请求  ----get
    @Event(value = R.id.btn_get,type = View.OnClickListener.class)
    private void  onHttpGet(View view){

//        org.xutils.http.RequestParams entity, 请求参数
//        org.xutils.common.Callback.CommonCallback callback  请求的回调
        RequestParams requestParams = new RequestParams(jsonPath);
        requestParams.setCacheDirName("httpCache"); //设置缓存路径名;
        requestParams.setCacheMaxAge(1000*60*30);//设置缓存最大存活时间
        requestParams.setCacheSize(1024*1024*5);//设置缓存的大小
        requestParams.setConnectTimeout(3*1000);//设置连接超时
        requestParams.setMaxRetryCount(3);//设置重复连接的次数\
        requestParams.setPriority(Priority.BG_TOP);//设置网络优先级
        requestParams.setCharset("UTF-8");//设置字符编码\

         cancelable = x.http().get(requestParams, new Callback.CommonCallback() {
            /*
            *数据请求成功的回调
            * */
            @Override
            public void onSuccess(String result) {
                //在主线程运行
                if (!TextUtils.isEmpty(result)) {
                    tvTest.setText(result);
                }
            }

            /*
            *数据请求错误的回调
            * */
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            /*
            *数据请求取消的回调
            * */
            @Override
            public void onCancelled(CancelledException cex) {

            }

            /*
            *数据请求完成
            * */
            @Override
            public void onFinished() {

            }
        });

       /* cancelable = x.http().get(requestParams, new Callback.CacheCallback() {
            @Override
            public boolean onCache(String result) {
                return false;
            }

            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
*/
    }

    /*
    *post请求
    * */
   @Event(value = R.id.btn_post,type = View.OnClickListener.class)
   private  void  onHttpPost(View view){
       //post测试
       //post提交的字段:pageNo=1&pageSize=20&serialIds=2143,3404&v=4.0.0
      // public final static  String pathPost = "http://mrobot.pcauto.com.cn/v2/cms/channels/1?";

       RequestParams requestParams = new RequestParams(pathPost);
        //添加post请求参数
       requestParams.addBodyParameter("pageNo","1");
       requestParams.addBodyParameter("pageSize","20");
       requestParams.addBodyParameter("serialIds","2143,3404");
       requestParams.addBodyParameter("v","4.0.0");

       x.http().post(requestParams, new Callback.CommonCallback() {
           @Override
           public void onSuccess(String result) {
               tvTest.setText(result);
           }

           @Override
           public void onError(Throwable ex, boolean isOnCallback) {

           }

           @Override
           public void onCancelled(CancelledException cex) {

           }

           @Override
           public void onFinished() {

           }
       });
   }




    @Override
    protected void onDestroy() {
        //取消请求
        cancelable.cancel();
        super.onDestroy();
    }
}
到此。

你可能感兴趣的:(android,高级之旅)