一個界面,實現在向頁面添加圖片時,在標題上顯示一個水平進度條,當圖片載入完畢后,隱藏進度條并顯示圖片
具體實現方法:
res/layout/main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:id="@+id/layout1" android:gravity="center"> </LinearLayout>
MainActivity:
package com.example.test; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.ImageView; import android.widget.LinearLayout; public class MainActivity extends Activity{ private int imageId[]=new int[]{R.drawable.img01,R.drawable.img02, R.drawable.img03,R.drawable.img04};//定義并初始化一個保存要顯示圖片id的數組 private LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS);//顯示水平進度條 setContentView(R.layout.main); layout=(LinearLayout)findViewById(R.id.layout1); new MyTack().execute(); } /* * 創建繼承自AsyncTask的異步類,并重寫onPreExecute()、doInBackground()、onProgressUpdate() * 和onPostExecute方法,實現在向頁面添加圖片時,在標題上顯示一個水平進度條,當圖片載入完畢后, * 隱藏進度條并顯示圖片 * */ //功能:創建異步任務,添加4張圖片 class MyTack extends AsyncTask<Void,Integer,LinearLayout>{ @Override protected void onPreExecute() { setProgressBarVisibility(true);//執行任務前讓進度條可見 super.onPreExecute(); } //功能:要執行的耗時任務(此方法異步執行) @Override protected LinearLayout doInBackground(Void... params) { LinearLayout layout2=new LinearLayout(MainActivity.this); for (int i = 1; i < 5; i++) { ImageView imageView=new ImageView(MainActivity.this);//創建一個ImageView對象 imageView.setLayoutParams(new LayoutParams(245,108)); imageView.setImageResource(imageId[i-1]);//設置要顯示的圖片 layout2.addView(imageView);//將imageView添加到線形布局管理器中 try { Thread.sleep(10);//為了更好的觀察到效果,我們讓線程休眠10毫秒 } catch (InterruptedException e) { e.printStackTrace(); } publishProgress(i);//觸發onProgressUpdate(Progress...)方法更新進度 } return layout2; } //功能:更新進度(此方法在主線程中運行) @Override protected void onProgressUpdate(Integer... values) { setProgress(values[0]*2500);//動態更新最新進度 super.onProgressUpdate(values); } //功能:執行任務后(此方法在主線程中運行) @Override protected void onPostExecute(LinearLayout result) { setProgressBarVisibility(false);//任務執行后隱藏進度條 layout.addView(result);//將水平線性布局管理器添加到布局文件中添加的垂直線性布局管理器中 super.onPostExecute(result); } } } 運行效果如下:
下圖是加載過程,標題欄上方有一個進度條顯示的是加載圖片的進度

下圖是加載完成,顯示出圖片

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答