XUTILS

xUtils 包含了很多实用的android工具.
xUtils 支持超大文件(超过2G)上传,更全面的http请求协议支持(11种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响…
xUtils 最低兼容Android 4.0 (api level 14). (Android 2.3?)
xUtils3变化较多所以建立了新的项目不在旧版(github.com/wyouflf/xUtils)上继续维护, 相对于旧版本:
HTTP实现替换HttpClient为UrlConnection, 自动解析回调泛型, 更安全的断点续传策略.
支持标准的Cookie策略, 区分domain, path…
事件注解去除不常用的功能, 提高性能.
数据库api简化提高性能, 达到和greenDao一致的性能.
图片绑定支持gif, webp; 支持圆角, 圆形, 方形等裁剪, 支持自动旋转…

使用Gradle构建时添加一下依赖即可:

compile ‘org.xutils:xutils:3.1.+’
// or
// compile ‘org.xutils:xutils:3.1.14’

先是如何取控件和添加点击事件

拿控件格式

  @ViewInject(R.id.shendf)
    var text: TextView? = null;

添加点击事件格式

@Event(value = [R.id.shendf])
    private fun initView(view: View){

        when(view.id){
            R.id.shendf->{
                Toast.makeText(this,"点击控件",Toast.LENGTH_SHORT).show()
                startActivity(Intent(this,ViewActivity::class.java))
            }
        }

    }
    注意 必须是private!!!!!!!!!!!!!!

HttpUtils(get和post)

@ContentView(R.layout.activity_http)
class HttpActivity : AppCompatActivity() {
    val url :String = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1"
    val post :String = "http://www.qubaobei.com/ios/cf/dish_list.php?"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        x.view().inject(this)
    }

    @Event(value = [R.id.btnget,R.id.btnpost],type = View.OnClickListener::class)
    private fun httpget(view: View){
        when(view.id){
            R.id.btnget->{
                getData();
            }
            R.id.btnpost->{
                postData();
            }
        }
    }

    private fun postData() {
        var requestParams = RequestParams();
        requestParams.uri = post;
//        stage_id=1&limit=20&page=1
        requestParams.addBodyParameter("stage_id","1");
        requestParams.addBodyParameter("page","1");

        x.http().post(requestParams, object :Callback.CommonCallback<String>{
            override fun onFinished() {

            }

            override fun onSuccess(result: String?) {
//                请求成功
                Toast.makeText(this@HttpActivity,result,Toast.LENGTH_SHORT).show();
                if (result != null) {
                    parseString(result)
                };
            }

            override fun onCancelled(cex: Callback.CancelledException?) {
//               取消请求
            }

            override fun onError(ex: Throwable?, isOnCallback: Boolean) {

                if (ex != null) {
                    ex.stackTrace
                };
            }

        })
    }

    private fun getData() {
        var requestParams = RequestParams(url);
//        requestParams.uri = url;

        x.http().get(requestParams, object :Callback.CommonCallback<String>{
            override fun onFinished() {

            }

            override fun onSuccess(result: String?) {
//                请求成功
                Toast.makeText(this@HttpActivity,result,Toast.LENGTH_SHORT).show();
                if (result != null) {
                    parseString(result)
                };
            }

            override fun onCancelled(cex: Callback.CancelledException?) {
//               取消请求
            }

            override fun onError(ex: Throwable?, isOnCallback: Boolean) {

                if (ex != null) {
                    ex.stackTrace
                };
            }

        })
    }
    fun parseString(string : String){
        val jsonObject = JSONObject(string)
        val jsonArray = jsonObject.getJSONArray("data")
        var array  = ArrayList<Bean>();
        for (i in 0..jsonArray.length()-1 step 1){
            val jso1 = jsonArray.getJSONObject(i)
            val title = jso1.getString("title")
            val pic = jso1.getString("pic")
            array.add(Bean(title,pic))
        }

        mylist.adapter = object :BaseAdapter(){
            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
                var vHolder:VHolder;
                var view:View;
                if(convertView == null){
                    vHolder = VHolder()
                    view = View.inflate(this@HttpActivity,R.layout.items,null)
                    vHolder.textView = view.findViewById(R.id.b_text)
                    vHolder.imageView = view.findViewById(R.id.b_pic)
                    view.tag = vHolder
                }else{
                    view = convertView
                    vHolder = view.tag as VHolder
                }

                vHolder.textView?.text = array[position].title
                Glide.with(this@HttpActivity).load(array[position].pic).into(vHolder.imageView)
                vHolder.imageView?.setOnClickListener {
                    var build = AlertDialog.Builder(this@HttpActivity);
                    val inflate = View.inflate(this@HttpActivity, R.layout.pics, null)
                    build.setView(inflate)
                    var pic :ImageView= inflate.findViewById(R.id.mypic)
                    Glide.with(this@HttpActivity).load(array[position].pic).into(pic)
                    build.create().show()
                }
                return view
            }

            override fun getItem(position: Int): Any {
                return array[position]
            }

            override fun getItemId(position: Int): Long {
                return position.toLong()
            }

            override fun getCount(): Int {
                return array.size
            }

        }
    }
    class VHolder{
        var textView:TextView? = null;
        var imageView:ImageView? = null;
    }

DBUtils

@ContentView(R.layout.activity_db)
class DBActivity : AppCompatActivity() {
    var db: DbManager?=null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        x.view().inject(this)
        initDB();
    }

    /**
     * 初始化数据库
     */
    private fun initDB(){

        val daoConfig = DbManager.DaoConfig()
        daoConfig.setDbName("UserDBUtils")
        daoConfig.setDbVersion(1)

        db = x.getDb(daoConfig)


    }
    @Event(value = [R.id.s_zeng,R.id.s_shan,R.id.s_gai,R.id.s_cha])
    private fun click(view: View){
        when(view.id){
            R.id.s_zeng->{
                  writeDB();
            }
            R.id.s_cha->{
                readDB();
            }
        }
    }

    private fun writeDB() {
        val userDBUtils = UserDBUtils()
        userDBUtils.id = 1
        userDBUtils.name = "申德丰"
        userDBUtils.age = "19"

        db?.save(userDBUtils);
        Toast.makeText(this,"存入数据库",Toast.LENGTH_SHORT).show()
    }

    private fun readDB() {

            val userDBUtils = db?.selector(UserDBUtils::class.java)?.findFirst()
            Toast.makeText(this,userDBUtils.toString(),Toast.LENGTH_SHORT).show()

    }
}

Bean类是关键

通过table和comple注解与数据库结合

@Table(name = "UserDBUtils")
public class UserDBUtils {
    @Column(name = "id",isId = true)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private String age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserDBUtils{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

还有就是

DownLoadUtils 断点续传

@ContentView(R.layout.activity_down_load)
class DownLoadActivity : AppCompatActivity() {
    var str :String=  Environment.getExternalStorageDirectory().path + "/qq.apk"
    var cancelable:Callback.Cancelable? = null
    var progressDialog :ProgressDialog ? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        x.view().inject(this)
        initProgressDialog();
    }
    private fun initProgressDialog(){

        progressDialog = ProgressDialog(this)
        progressDialog?.setTitle("下载apk")
        progressDialog?.setMessage("Lodaing")
        progressDialog?.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
        progressDialog?.setCanceledOnTouchOutside(false)
        progressDialog?.setButton(ProgressDialog.BUTTON_NEGATIVE,"暂停", object :DialogInterface.OnClickListener{
            override fun onClick(dialog: DialogInterface?, which: Int) {
                cancelable?.cancel()
            }

        })


    }
    @Event(value = [R.id.download])
    private fun click(view: View){
        downloadAPK();
    }

    private fun downloadAPK() {
        //设置参数
        var requestParams = RequestParams();
        requestParams.uri = "http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk"
//        设置断点续传
        requestParams.isAutoRename = true
        requestParams.saveFilePath = str
        requestParams.isCancelFast = true

        cancelable = x.http().get(requestParams, object : Callback.ProgressCallback<File> {
            override fun onFinished() {
                progressDialog?.cancel();
            }

            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                progressDialog?.setProgress( (current * 100 / total).toInt());
            }

            override fun onStarted() {
                progressDialog?.show();

            }

            override fun onSuccess(result: File?) {
                Toast.makeText(this@DownLoadActivity, "下载成功了" + result?.getAbsolutePath(), Toast.LENGTH_SHORT).show()

                val intent = Intent()
                intent.action = Intent.ACTION_VIEW
                intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive")
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                this@DownLoadActivity.startActivity(intent)
            }

            override fun onWaiting() {

            }

            override fun onCancelled(cex: Callback.CancelledException?) {

            }

            override fun onError(ex: Throwable?, isOnCallback: Boolean) {
                ex?.stackTrace
            }

        })
    }
}

INTERESTING!!!

xUtils包含了orm,http(s),image,view注解,但依然很轻量级(251K),并且特性强大,方便扩展。xUtils特点1、orm:高效稳定的orm工具,使得http接口实现时更方便的支持cookie和缓存。 灵活的,类似linq表达式的接口。 和greenDao一致的性能。 2、http(s):基于UrlConnection,Android4。4以后底层为okHttp实现。 请求协议支持11种谓词:GET,POST,PUT,PATCH,HEAD,MOVE,COPY,DELETE,OPTIONS,TRACE,CONNECT 支持超大文件(超过2G)上传 支持断点下载(如果服务端支持Range参数,客户端自动处理断点下载) 支持cookie(实现了domain,path,expiry等特性) 支持缓存(实现了Cache-Control,Last-Modified,ETag等特性,缓存内容过多时使用过期时间+LRU双重机制清理) 支持异步和同步(可结合RxJava使用)调用 3、image:有了http(s)及其下载缓存的支持,image模块的实现相当的简洁。 支持内存缓存,磁盘缓存(缩略图和原图),并且支持回收被view持有,但被MemCache移除的图片,减少页面回退时的闪烁。 支持在ListView滑动时,自动停止被回收复用的item对应的下载任务(再次下载时断点续传) 支持webp,gif(部分比较老的系统只展示静态图) 支持圆角,圆形,方形等裁剪,支持自动旋转... 4、view注解:view注解模块仅仅400多行代码却灵活的支持了各种View注入和事件绑定。 事件注解支持且不受混淆影响...(参考混淆配置) 支持绑定拥有多个方法的listener
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值