从活动中保存图像时显示ProgressBar

时间:2013-09-04 01:49:01

标签: java android

在我的应用中,我让用户保存图纸。保存图形时,我想在图形顶部显示一个进度条,让用户知道它正在保存。

我的XML布局:

<FrameLayout
    android:id="@+id/viewd"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="3"
    android:orientation="vertical"
    android:layout_gravity="center" >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="0dp"
        android:background="@drawable/bd"
        android:id="@+id/llFreeDraw" >
    </LinearLayout>
    <ProgressBar 
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        style="@android:style/Widget.ProgressBar.Large"
        android:id="@+id/pbSave"
        android:visibility="invisible" />
</FrameLayout>

我的Java代码部分是:

View.OnClickListener saveHandle = new View.OnClickListener() {
    public void onClick(View v) {
        savePB = (ProgressBar) findViewById(R.id.pbSave);
        savePB.setVisibility(View.VISIBLE);
        View content = layout;
        content.setDrawingCacheEnabled(true);
        content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = content.getDrawingCache();
        File folder = new File(Environment.getExternalStorageDirectory() + "/PB");
        if (!folder.exists()) {
            folder.mkdir();
        }
        file = new File(folder + "/pb_image_" + Math.random()  + ".png");
        FileOutputStream ostream;
        try {
            file.createNewFile();
            ostream = new FileOutputStream(file);
            bitmap.compress(CompressFormat.PNG, 100, ostream);
            ostream.flush();
            ostream.close();
            displayToast("Image was saved.");
            savePB.setVisibility(View.GONE);
            btnSave.setVisibility(View.GONE);
            btnShare.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
            displayToast("Unable to save image. Try again later.");
        }
    }
};

我想在framelayou上显示进度条,背景为25%透明。图像正在保存,但我没有看到进度条。任何想法如何修改所以它按照我想要的方式工作?

1 个答案:

答案 0 :(得分:3)

AsyncTask可以解决此问题。

public class SaveImageTask extends AsyncTask<Void, Void, Void> {
     @Override
     protected Void doInBackground(Void... params) {
         // Save your image here.
         return null;
     }

     @Override
     protected void onPreExecute(){
         // Show your progress bar here.
     }

     @Override
     protected void onPostExecute() {
         // Hide the progress bar here.      
     }
 }

称之为:

new SaveImageTask().execute(null, null, null);