android重新整理UI的幾種方式總結

來源:互聯網
上載者:User

標籤:多線程   android   

首先,android的UI重新整理是在主線程(UI線程)中完成的。四大組件中,activity和service運行在主線程中。現在總結自己在項目中常用到的UI重新整理方式。

第一,利用子線程發訊息重新整理UI。

子線程負責處理UI需要的資料,然後發訊息到主線程來重新整理UI。代碼結構如下:

new Thread(new Runnable() {@Overridepublic void run() {Person person=new Person();person.setName(mName.getText().toString().trim());person.setPhone(mPhone.getText().toString().trim());Log.i("person",person.toString());DatabaseInfoFactory.getPersonDao(mContext).addPerson(person);Looper.prepare();Message msg=Message.obtain();msg.what=0x123456;handler.sendMessage(msg);Looper.loop();}}).start();


主線程中:

private Handler mHandler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);if(msg.what==0x123456||msg.what==0x123){fillData();setListener();}}};

第二,利用非同步任務更新UI。代碼結構如下:

new AsyncTask<Void,Void,Void>() {@Overrideprotected void onPostExecute(Void result) {if(mAdapter==null){mAdapter=new LeaveInfoAdapter();//設定資料配接器mLVleaveInfos.setAdapter(mAdapter);Log.i("測試", "非同步任務顯示後台獲得資料庫資料");}else {mAdapter.notifyDataSetChanged();}super.onPostExecute(result);}@Overrideprotected Void doInBackground(Void... params) {//獲得要顯示的資料mleaveInfos=mLeaveInfosDao.findAll();if (mleaveInfos==null) {Toast.makeText(HomeActivity.this,"請假資料不存在或是已經清除!", 500).show();}Log.i("測試", "非同步任務後台獲得資料庫資料"+mleaveInfos.size());return null;}}.execute();


第三,利用設定檔+activity的生命週期方法重新整理UI。




android重新整理UI的幾種方式總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.