Android系统。 ProgressBar不起作用?

时间:2014-04-04 17:40:01

标签: android

我从数据库中加载了一些数据,我想在此期间显示一个圆形动画,因为这需要时间。圆圈出现但仅在loadContent()加载数据之后。

代码:

final String PREFS_NAME = "MyPrefsFile";

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

    ProgressBar p = (ProgressBar) findViewById(R.id.imgProgress);
    p.setEnabled(true);


    if (settings.getBoolean("my_first_time", true)) {

        // the app is being launched for first time, do something
        Log.d("Launched:", "first time");

        loadContent();

        // record the fact that the app has been started at least once
        settings.edit().putBoolean("my_first_time", false).commit();
    }
    p.setEnabled(false);

在XML中:

<ProgressBar
    android:id="@+id/imgProgress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_centerInParent="true"
    android:layout_height="wrap_content" />

2 个答案:

答案 0 :(得分:0)

我不知道loadContent方法是什么,但我建议你做AsyncTask(如果不是这样的话)。您可以按如下方式显示/隐藏ProgressBar

// loadContent method
public class loadContent extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        // set your progress bar to visible
        ((ProgressBar) findViewById(R.id.imgProgress)).setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        // do some stuff: load datas from sql, load images.. whatever
        // and return a string value for onPostExecute (string = "Loaded"
        return string;
    }

    @Override
    protected void onPostExecute(String result) {
        if(result.equals("Loaded") {
            // the loading is finish, display your datas
            // set your progress bar to gone
            ((ProgressBar) findViewById(R.id.imgProgress)).setVisibility(View.GONE);
        }
    }
}  

Herehere,您将看到一个AsyncTask方法的好例子。然后,您只需将visibility属性添加到视图中:

<ProgressBar
    android:id="@+id/imgProgress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_centerInParent="true"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:visibility="gone" />  

希望这有帮助。

答案 1 :(得分:0)

为什么不这样做呢?

public class SomeTask extends AsyncTask<Void, String, Void>{

        ProgressDialog dialogue;

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            dialogue.dismiss();

            //If Using some adapter; someadapteradapter.notifyDataSetChanged();
        }

        @Override
        protected void onPreExecute() {
            dialogue = new ProgressDialog(ProgressBar.this);
            dialogue.setTitle("Loading items..");
            dialogue.show();
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {

            //Your task!!

            return null;


        }
    }

比这更简单......:)