Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> xUtils3.0框架學習筆記分享

xUtils3.0框架學習筆記分享

編輯:關於Android編程

xUtils是開速開發安卓項目的開源框架,開源項目地址:https://github.com/wyouflf/xUtils3。使用起來非常方便。主要功能包括:

1、xUtils 支持超大文件(超過2G)上傳,更全面的http請求協議支持(11種謂詞)。

2、擁有更加靈活的ORM,更多的事件注解支持且不受混淆影響。

3、圖片綁定支持gif(受系統兼容性影響, 部分gif文件只能靜態顯示), webp; 支持圓角, 圓形, 方形等裁剪, 支持自動旋轉等。

4、數據庫api簡化提高性能, 達到和greenDao一致的性能。

5、HTTP實現替換HttpClient為UrlConnection, 自動解析回調泛型, 更安全的斷點續傳策略等。 

控件及事件注解綁定,方便高效HTTP請求,簡單地數據庫操作方式,確實是一款非常有助於我們快速開發項目的開源框架。 
參考github上面demo及相關資料,寫了一個學習的demo,分別從注解,圖片,HTTP及數據庫四個方面進行了代碼編寫。

首先是在AndroidStudio中配置項目:
第一步:
在AndroidStudio項目的build.gradle文件中添加compile ‘org.xutils:xutils:3.3.36':

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 testCompile 'junit:junit:4.12'
 compile 'com.android.support:appcompat-v7:23.4.0'
 compile 'org.xutils:xutils:3.3.36'
}

添加好後build下工程即可。

第二步:
在AndroidManifest.xml中添加對應權限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

第三步:在項目中自定義Application,初始化xUtils3.0。

/**
 * description:
 * 作者:ldm
 * 時間:20162016/6/22 09:03
 * 郵箱:[email protected]
 */
public class BaseApplication extends Application {
 @Override
 public void onCreate() {
 super.onCreate();
 x.Ext.init(this);//在自定義的Application中初始化XUtils3.0
 }
}

記得把我們定義的Application配置到AndroidManifest.xml中。
接下來就可以作用xUtils3.0進行快速開發了。

—– 第一部分:注解示例—–

/**
 * description:xUtils3.0框架注解功能
 * 作者:ldm
 * 時間:20162016/6/22 09:17
 * 郵箱:[email protected]
 */
@ContentView(R.layout.activity_annotation)
public class AnnotationActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 x.view().inject(this);
 FragmentManager fragmentManager = getFragmentManager();
 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 TestFragment fragment = new TestFragment();
 fragmentTransaction.add(R.id.fra_layout, fragment);
 fragmentTransaction.commit();
 }
}

—–注解功能對應地Fragment—–

/**
 * description:xUtils3.0框架注解之:Fragment中注解使用
 * 作者:ldm
 * 時間:20162016/6/22 09:28
 * 郵箱:[email protected]
 */
@ContentView(R.layout.frag_test)//給Fragment綁定布局文件
public class TestFragment extends Fragment {
 @ViewInject(R.id.test_listview)
 private ListView listView;
 private List<ListBean> datas;

 public TestFragment() {
 super();
 }

 @Nullable
 @Override
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 return x.view().inject(this, inflater, container);//調用x.view().inject()方法返回view
 }

 //onCreateView是創建的時候調用,onViewCreated是在onCreateView後被觸發的事件
 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
 super.onViewCreated(view, savedInstanceState);
 constructDatas();
 listView.setAdapter(new TestAdapter(getActivity(), datas));
 }

 private void constructDatas() {
 datas = new ArrayList<>();
 for (int i = 0; i < 15; i++) {
 ListBean bean = new ListBean("這是第" + i + "個標題", "這裡都是相同的內容");
 datas.add(bean);
 }
 }

 //ListView的item點擊事件注解操作
 @Event(type = AdapterView.OnItemClickListener.class, value = R.id.test_listview)
 private void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 Toast.makeText(getActivity(), "點擊了第" + position + "個item", Toast.LENGTH_LONG).show();
 }

 //長按事件注解操作
 @Event(type = AdapterView.OnItemLongClickListener.class, value = R.id.test_listview)
 private boolean onLongItemClick(AdapterView<?> parent, View view, int position, long id) {
 Toast.makeText(getActivity(), "長按第" + position + "個item", Toast.LENGTH_LONG).show();
 return true;
 }
}

—–第二部分:圖片加載示例—–

/**
 * description:xUtils3.0框架圖片功能
 * 作者:ldm
 * 時間:20162016/6/22 09:17
 * 郵箱:[email protected]
 */
@ContentView(R.layout.activity_image)
public class ImageActivity extends Activity {
 @ViewInject(R.id.image_01)
 private ImageView image_01;
 @ViewInject(R.id.image_02)
 private ImageView image_02;
 @ViewInject(R.id.image_03)
 private ImageView image_03;
 @ViewInject(R.id.image_04)
 private ImageView image_04;
 private String url_01 = "";
 private String url_02 = "";
 private String url_03 = "";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 x.view().inject(this);//需要添加這句代碼,否則不會關聯到布局
 }

 //加載網絡圖片第一種方法
 @Event(value = R.id.image_01)
 private void loadImageMethodOne(View v) {
 //直接調用 bind(ImageView view, String url)方法,傳入對應控件及url即可
 x.image().bind(image_01, url_01);
 }

 //加載網絡圖片第二種方法
 @Event(value = R.id.image_02)
 private void loadImageMethodTwo(View v) {
 //創建圖片參數設置類ImageOptions
 ImageOptions options = new ImageOptions.Builder().build();
 //直接調用bind(ImageView view, String url, ImageOptions options)方法,傳入對應參數
 x.image().bind(image_02, url_02, options);
 }

 //加載網絡圖片第三種方法
 @Event(value = R.id.image_03)
 private void loadImageMethodThree(View v) {
 //調用bind(ImageView view, String url, Callback.CommonCallback<Drawable> callback)
 x.image().bind(image_03, url_03, new Callback.CacheCallback<Drawable>() {
 @Override
 public boolean onCache(Drawable result) {//可以在這裡設置圖片保存等操作
 return false;
 }

 @Override
 public void onSuccess(Drawable result) {//獲取成功

 }

 @Override
 public void onError(Throwable ex, boolean isOnCallback) {//獲取失敗

 }

 @Override
 public void onCancelled(CancelledException cex) {//取消操作

 }

 @Override
 public void onFinished() {//完成操作

 }
 });
 }

 //加載本地圖片
 @Event(value = R.id.image_04)
 private void loadImageMethodFour(View v) {
 ImageOptions options = new ImageOptions.Builder().
 setImageScaleType(ImageView.ScaleType.FIT_CENTER).
 setUseMemCache(true).
 build();//可以設置options各項參數
 // assets下的圖片
 // x.image().bind(image_04, "assets://test.png", options);
 // SD卡下圖片
 // x.image().bind(image_04, new File("/sdcard/test.png").toURI().toString(), options);
 x.image().bind(image_04, "/sdcard/test.gif", options);
 }
}

—–第三部分:HTTP請求—–

/**
 * description:xUtils框架之Http請求
 * 作者:ldm
 * 時間:20162016/6/22 09:17
 * 郵箱:[email protected]
 */
@ContentView(R.layout.activity_http)
public class HttpActivity extends Activity {
 @ViewInject(R.id.get)
 private Button get;
 @ViewInject(R.id.post)
 private Button post;
 @ViewInject(R.id.upload)
 private Button upLoad;
 @ViewInject(R.id.download)
 private Button downLoad;
 private static final String TAG = "HttpActivity";

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

 //HTTP請求之GET請求
 @Event(type = View.OnClickListener.class, value = R.id.get)
 private void httpGetOnClick(View v) {
 String url = "http://www.baidu.com";
 final ProgressDialog dia = new ProgressDialog(this);
 dia.setMessage("加載中....");
 dia.show();
 RequestParams params = new RequestParams(url);
 x.http().get(params, new Callback.CommonCallback<String>() {
 @Override
 public void onSuccess(String result) {
 //加載成功回調,返回獲取到的數據
 Log.i(TAG, "onSuccess: " + result);
 }

 @Override
 public void onFinished() {
 dia.dismiss();//加載完成
 }

 @Override
 public void onCancelled(CancelledException cex) {

 }

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

 }
 });
 }

 //HTTP請求之POST請求
 @Event(type = View.OnClickListener.class, value = R.id.post)
 private void httpPostOnClick(View v) {
 String url = "this is request url for post";
 final ProgressDialog dia = new ProgressDialog(this);
 dia.setMessage("加載中....");
 dia.show();
 RequestParams params = new RequestParams(url);
 params.addParameter("userName", "admin");//添加Post請求參數,如果是get請求,會直接添加到url後面
 params.addBodyParameter("passWord", "123456");
 params.addHeader("head", "給Head添加信息");//addHeader添加Head信息
 x.http().post(params, new Callback.CommonCallback<String>() {
 @Override
 public void onSuccess(String result) {
 //加載成功回調,返回獲取到的數據
 Log.i(TAG, "onSuccess: " + result);
 }

 @Override
 public void onFinished() {
 dia.dismiss();//加載完成
 }

 @Override
 public void onCancelled(CancelledException cex) {

 }

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

 }
 });
 }

 //HTTP請求之文件上傳
 @Event(type = View.OnClickListener.class, value = R.id.upload)
 private void upLoadOnClick(View v) {
 String upUrl = "/mnt/sdcard/pic/test.jpg";//指定要上傳的文件
 final ProgressDialog dia = new ProgressDialog(this);
 dia.setMessage("加載中....");
 dia.show();
 RequestParams params = new RequestParams(upUrl);
 params.addBodyParameter("file", new File(upUrl));
 x.http().post(params, new Callback.CommonCallback<String>() {
 @Override
 public void onSuccess(String result) {
 //加載成功回調,返回獲取到的數據
 Log.i(TAG, "onSuccess: " + result);
 }

 @Override
 public void onFinished() {
 dia.dismiss();//加載完成
 }

 @Override
 public void onCancelled(CancelledException cex) {

 }

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

 }
 });
 }

 //HTTP請求之文件下載
 @Event(type = View.OnClickListener.class, value = R.id.download)
 private void downLoadOnClick(View v) {
 String downUrl = "please input download url";
 final ProgressDialog dia = new ProgressDialog(this);
 dia.setMessage("加載中....");
 dia.show();
 RequestParams params = new RequestParams(downUrl);
 x.http().post(params, new Callback.CommonCallback<File>() {
 @Override
 public void onSuccess(File result) {
 //下載成功
 Intent in = new Intent(Intent.ACTION_VIEW);
 in.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");//比如我們下載的apk文件,直接安裝
 startActivity(in);
 }

 @Override
 public void onFinished() {
 dia.dismiss();
 }

 @Override
 public void onCancelled(CancelledException cex) {

 }

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

 }
 });
 }
}

—-第四部分:數據庫操作——

/**
 * description:xUtils3.0框架數據庫操作
 * 作者:ldm
 * 時間:20162016/6/22 09:17
 * 郵箱:[email protected]
 */

@ContentView(R.layout.activity_db)
public class DatabaseActivity extends Activity {
 @ViewInject(R.id.create)
 private Button create;
 @ViewInject(R.id.add)
 private Button add;
 @ViewInject(R.id.delete)
 private Button delete;
 @ViewInject(R.id.query)
 private Button query;
 @ViewInject(R.id.update)
 private Button update;
 @ViewInject(R.id.del_db)
 private Button del_db;
 private DbManager.DaoConfig daoConfig;

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

 private void initDataBase() {
 daoConfig = new DbManager.DaoConfig()
 .setDbName("test.db")//數據庫名稱
 // 不設置dbDir時, 默認存儲在app的私有目錄.
 .setDbDir(new File("/sdcard")) // "sdcard"的寫法並非最佳實踐, 這裡為了簡單, 先這樣寫了.
 .setDbVersion(2)//設置版本號
 .setDbOpenListener(new DbManager.DbOpenListener() {
  @Override
  public void onDbOpened(DbManager db) {
  // 開啟WAL, 對寫入加速提升巨大
  db.getDatabase().enableWriteAheadLogging();
  }
 })
 .setDbUpgradeListener(new DbManager.DbUpgradeListener() {//數據庫升級
  @Override
  public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
  // TODO: ...
  // db.addColumn(...);
  // db.dropTable(...);
  // ...
  // or
  // db.dropDb();
  }
 });
 }

 //創建數據庫及表格
 @Event(value = R.id.create)
 private void createOnClick(View v) throws Exception {
 initDataBase();
 DbManager db = x.getDb(daoConfig);
 Teacher t = new Teacher("張三", 28, "English", 1);
 db.save(t);//調用這句話,則可以創建表格,並把數據存入
 }

 //添加數據
 @Event(value = R.id.add)
 private void addOnClick(View v) throws Exception {
 DbManager db = x.getDb(daoConfig);
 Teacher t = new Teacher("李四", 38, "Math", 3);
 db.save(t);//如果表格存在,並把數據存入
 List<Teacher> list = new ArrayList<>();
 list.add(new Teacher("王五", 30, "Engilsh", 2));
 list.add(new Teacher("趙六", 40, "Chinese", 3));
 list.add(new Teacher("陳七", 50, "Math", 4));
 db.save(list);//可以這樣保存多條數據到指定表格
 }

 //刪除數據
 @Event(value = R.id.delete)
 private void deleteOnClick(View v) throws Exception {
 DbManager db = x.getDb(daoConfig);
 WhereBuilder wb = WhereBuilder.b();
 wb.and("level", "=", 1);
 db.delete(Teacher.class, wb);//刪除等級為1的教師
 }

 //修改數據
 @Event(value = R.id.update)
 private void updateOnClick(View v) throws Exception {
 DbManager db = x.getDb(daoConfig);
 db.update(Teacher.class, WhereBuilder.b().and("name", "=", "王五"), new KeyValue("name", "朱八"));//把王五的名字改成朱八
 }

 //查詢數據
 @Event(value = R.id.query)
 private void queryOnClick(View v) throws Exception {
 DbManager db = x.getDb(daoConfig);
 WhereBuilder wb = WhereBuilder.b();
 wb.and("level", "=", 2);
 List<Teacher> list = db.selector(Teacher.class).findAll();//查詢所有數據
 List<Teacher> list1 = db.selector(Teacher.class).where(wb).findAll();//查詢等級數2的教師
 }

 //刪除數據庫或表格
 @Event(value = R.id.del_db)
 private void delDBOnClick(View v) throws Exception {
 DbManager db = x.getDb(daoConfig);
 db.dropDb();//刪除數據庫
 db.dropTable(Teacher.class);//刪除teacher表格
 }


}

由於時間關系,代碼寫得比較粗糙,後期使用中再細化。

Demo下載地址:http://xiazai.jb51.net/201611/yuanma/XutilsDemo(jb51.net).rar

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved