ProgressBar的可见性

MyW*_*Way 5 android android-progressbar

当用户在一个活动中单击按钮时,我需要处理一些数据,因此屏幕看起来像应用程序停止2-3秒.它并不是很多,但我想向用户提供一切正常的信息,IMO最好的方法是只有在处理数据时才能看到的进度条.

我找到了ProgressBar的代码,它看起来像这样:

    <ProgressBar
    android:id="@+id/loadingdata_progress"
    style="?android:attr/progressBarStyle"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignBottom="@+id/fin2_note"
    android:layout_centerHorizontal="true"
    android:indeterminate="true"
    android:visibility="invisible" />
Run Code Online (Sandbox Code Playgroud)

并将其插入我的布局中间.

并尝试进度条的工作原理,我把这个代码

loadingimage= (ProgressBar) findViewById(R.id.loadingdata_progress); loadingimage.setVisibility(View.VISIBLE);

进入onCreate方法,一切都很好.然后我重新创建代码以仅在处理数据时显示此进度条.

单击后,用户调用此方法

   public void fin2_clickOnFinalization(View v)
   {    

            loadingimage= (ProgressBar) findViewById(R.id.loadingdata_progress);
    loadingimage.setVisibility(View.VISIBLE);

          // code where data is processing
            loadingimage.setVisibility(View.INVISIBLE);
       }
Run Code Online (Sandbox Code Playgroud)

并且屏幕上没有任何内容.我不知道哪里出错了.如果我通过id找到了进度条,对我来说很奇怪,我可以在onCreate方法中控制它,但是在onclick方法中它不受我的控制.

ssw*_*zek 8

您的UI线程无法显示进度条,因为您的数据处理繁忙.尝试使用这种代码:

public void fin2_clickOnFinalization(View v) {

    new YourAsyncTask().execute();
}

private class YourAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... args) {
        // code where data is processing
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {         
        loadingimage.setVisibility(View.INVISIBLE);
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingimage.setVisibility(View.VISIBLE);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

AsyncTask允许您在单独的线程中运行代码并使应用程序更具响应性,只需将耗时的代码放入其中doInBackground.