如何在ListView加载数据之前,在Activity中显示圆形进度条?

146

我在第二个活动中有一个ListView。当我点击它时,我调用了一个Web服务并尝试获取数据。然后我跳转到第三个活动,该活动也有一个ListView,其中包含前一个活动的ListView项目的描述。

我想在填充此ListView之前显示进度对话框。

我不知道如何在ListView上实现。有人知道怎么做吗?

我的代码-

ThirdActivity.java

   package com.google.iprotect;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import com.google.iprotect.layout.TitleBarLayout;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class ThirdActivity extends ListActivity implements OnItemClickListener{

    JSONArray jArray1,jArray2;
    String one,two,three,tablename;
    String color,r;
    JSONObject responseJSON;
    TitleBarLayout titlebarLayout;
    final ArrayList<Tables> arraylist = new ArrayList<Tables>();
    TextView tableName;
    ColorStateList colorStateList1;
    String email1,password1;
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thirdactivity);

        ListView lv=getListView();
        lv.setOnItemClickListener(this);


        tablename=getIntent().getExtras().getString("Table Name");
        email1 = getIntent().getExtras().getString("email");
        password1 =getIntent().getExtras().getString("password");

        titlebarLayout = new TitleBarLayout(ThirdActivity.this);
        titlebarLayout.setLeftButtonText("go Back");
        titlebarLayout.setRightButtonText("Logout");
        titlebarLayout.setTitle(tablename);
        titlebarLayout.setLeftButtonSize(70,40);
        titlebarLayout.setRightButtonSize(70,40);
        //titlebarLayout.setLeftButtonLeftDrawable(R.drawable.refresh);

        //titlebarLayout.setRightButtonLeftDrawable(R.drawable.buttonrefresh);
        //titlebarLayout.setLeftButtonBackgroundColor(Color.rgb(255,255,255));
        //titlebarLayout.setRightButtonBackgroundColor(Color.rgb(34,49,64));
        //titlebarLayout.setLeftButtonTextColor(Color.rgb(255,255,255));
        //titlebarLayout.setRightButtonTextColor(Color.rgb(255,255,0));     

        XmlResourceParser parser1 =getResources().getXml(R.color.colorstatelist);


        try {
            colorStateList1 = ColorStateList.createFromXml(getResources(), parser1);
            titlebarLayout.setRightButtonTextColor(colorStateList1);
        } catch (XmlPullParserException e) {    
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

        OnClickListener listener = new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (v.getId() == R.id.left_button) {
                    Intent intent = new Intent(ThirdActivity.this,SecondActivity.class);
                    intent.putExtra("email", email1);
                    intent.putExtra("password", password1);
                    startActivity(intent);
                    finish();

                } else if (v.getId() == R.id.right_button) {
                    Intent intent = new Intent(ThirdActivity.this,
                            MainActivity.class);
                    //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    ThirdActivity.this.startActivity(intent);

                }
            }
        };
        titlebarLayout.setLeftButtonOnClickListener(listener);
        titlebarLayout.setRightButtonOnClickListener(listener);


        updateTableList();




    }

    private void updateTableList() {
        // TODO Auto-generated method stub
        //final ProgressDialog pd1=ProgressDialog.show(this, "Calling Webservice", "Waiting...", true, false);

        final ProgressBar pbHeaderProgress = (ProgressBar) findViewById(R.id.pbHeaderProgress);

        new AsyncTask<Void, Void, Void>() {


            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                pbHeaderProgress.setVisibility(View.VISIBLE);
            }



            protected Void doInBackground(Void... params) {
                r = invokeWebService1(tablename);
                //pd1.dismiss();

                try {
                    responseJSON = new JSONObject(r);
                    //json reading
                    jArray1 = responseJSON.getJSONArray("FirstThree");//get JSONArray jArray1 from JSONObject with name FirstThree
                    jArray2 = responseJSON.getJSONArray("Color");//get JSONArray jArray2 from JSONOobject with name Color
                    JSONObject json_data1 = null;
                    JSONObject json_data2 = null;

                    for (int i = 0; i < jArray1.length(); i++) {
                        json_data1 = jArray1.getJSONObject(i);//get JSONObject json_data1 from JSONArray at index i;
                        one = json_data1.getString("One");//get value from JSONObject json_data1 with key "One"
                        two = json_data1.getString("Two");
                        three = json_data1.getString("Three");
                        json_data2 = jArray2.getJSONObject(i);
                        color = json_data2.getString("color");//get value from JSONObject json_data2 with key "color"

                        Tables tables = new Tables();
                        //set value to Tables Class
                        tables.column1 = one;
                        tables.column2 = two;
                        tables.column3 = three;
                        tables.tableName=tablename;
                        tables.color=color;
                        //add Tables object into ArrayList<Tables>
                        arraylist.add(tables);

                        Log.i("ONE", json_data1.getString("One"));
                        Log.i("TWO", json_data1.getString("Two"));
                        Log.i("THREE", json_data1.getString("Three"));
                        Log.i("color",""+ json_data2.getString("color"));
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            protected void onPostExecute(Void result) {
                pbHeaderProgress.setVisibility(View.GONE);

                //Custom Adapter for ListView
                TableDetailAdapter adaptor = new TableDetailAdapter(ThirdActivity.this,
                        R.layout.table_data_list_item, arraylist);
                setListAdapter(adaptor);
            }
        }.execute();

    }

    protected String invokeWebService1(String tablename2) {
        // TODO Auto-generated method stub
        String response = "";
        try {
            WebService webService = new WebService(
            "http://sphinx-solution.com/iProtect/api.php?");

            // Pass the parameters if needed
            Map<String, String> params = new HashMap<String, String>();
            params.put("action", "getTableRecords");
            params.put("tablename", tablename2);
            params.put("email", email1);
            params.put("password", password1);

            // Get JSON response from server the "" are where the method name
            // would normally go if needed example
            response = webService.WebGet("auth", params);

        } catch (Exception e) {
            Log.d("Error: ", e.getMessage());
        }
        return response;
    }


    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        // TODO Auto-generated method stub

        Log.v("", "Click ListItem Number "+position);
        Intent intent = new Intent(ThirdActivity.this,FourthActivity.class);
        intent.putExtra("Json", responseJSON.toString());//sending json Object as a string to next activity
        intent.putExtra("Table Name", tablename);
        intent.putExtra("email", email1);
        intent.putExtra("password", password1);
        intent.putExtra("Item No", position);
        startActivity(intent);

    }

}

thirdactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linlaHeaderProgress"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ThirdActivity" >

    <include
        android:id="@+id/titlebar"
        layout="@layout/titlebar_layout" />

    <ProgressBar
        android:id="@+id/pbHeaderProgress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="2" >
    </ProgressBar>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="260dp" 
        android:layout_weight="5.04">
    </ListView>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="@dimen/titlebar_height"
        android:layout_alignParentBottom="true"
        android:background="@color/footer_bg_color"
        android:gravity="bottom"
        android:orientation="horizontal" >

        <include
            android:id="@+id/footer"
            android:layout_height="@dimen/titlebar_height"
            android:layout_gravity="bottom|center_horizontal"
            layout="@layout/footer_layout" />
    </LinearLayout>

</LinearLayout>

你在网上搜索过这个问题吗?https://dev59.com/2FrUa4cB1Zd3GeqPiENt - Pankaj Kumar
4
我知道如何显示进度对话框,但我希望只显示进度条圆圈,而不是进度对话框。 - Ani
请查看此链接:https://www.freakyjolly.com/show-progress-bar-with-text-and-title-in-android/ - Code Spy
12个回答

176

在加载 activity 时,有几种显示进度条(圆形)的方法。对于你的情况,是一个带有 ListViewactivity

在 ActionBar 中

如果您正在使用 ActionBar,则可以像这样调用 ProgressBar(可以将此代码放在您的 onCreate() 中):

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
setProgressBarIndeterminateVisibility(true);

在显示列表后,如果要隐藏它。

setProgressBarIndeterminateVisibility(false);

在布局文件中(XML中)

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone" >

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </ProgressBar>
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        android:divider="#00000000"
        android:dividerHeight="0dp"
        android:fadingEdge="none"
        android:persistentDrawingCache="scrolling"
        android:smoothScrollbar="false" >
    </ListView>
</LinearLayout>

在你的活动(Java)中,我使用一个AsyncTask来获取我的列表的数据。所以,在AsyncTask的onPreExecute()中,我使用以下代码:

// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);

@Override
protected void onPreExecute() {    
    // SHOW THE SPINNER WHILE LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.VISIBLE);
}

onPostExecute()方法中,在将适配器设置到ListView之后:

@Override
protected void onPostExecute(Void result) {     
    // SET THE ADAPTER TO THE LISTVIEW
    lv.setAdapter(adapter);

    // CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
    loadingMore = false;

    // HIDE THE SPINNER AFTER LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.GONE);
}

编辑:这是在我的应用程序加载其中一个ListViews时的效果

输入图像描述


2
我的应用程序中没有ActionBar。我想在屏幕中央显示进度条圆圈。 - Ani
1
@ShajeelAfzal:是的,这是一种风格。您可以在任何ICS API的SDK中找到它。搜索此XML:progress_medium_holo.xml,并将相关图像复制到其各自的drawable文件夹中。 - Siddharth Lele
SherlockListFragment怎么样?如何在其中实现。 - Pratik Butani
1
@eddy 只需在 ProgressBar 节点中使用 style="?android:attr/progressBarStyleLarge" 即可。 - Paul Gregoire
4
请问您能告诉我们 @style/Spinner 的定义是什么吗? - Pankaj
显示剩余21条评论

40
你可以更轻松地完成这个任务。
来源:http://www.tutorialspoint.com/android/android_loading_spinner.htm
它对我有所帮助。

布局:

<ProgressBar
   android:id="@+id/progressBar1"
   style="?android:attr/progressBarStyleLarge"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true" />
在xml中定义进度条后,您需要通过ProgressBar类在Java文件中获取其引用。以下是其语法:
private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);
之后,您可以通过setVisibility方法使其消失,并在需要时将其恢复。其语法如下所示:
spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);

虽然这不是最好的答案,但它确实帮助我解决了问题。谢谢。 - Machado

21

我在列表视图加载时使用了这个,可能会有帮助。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp" >

<LinearLayout
    android:id="@+id/progressbar_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ProgressBar
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="Loading data..." />
    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#C0C0C0" />
</LinearLayout>

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="1dip"
    android:visibility="gone" />

</RelativeLayout>

我的 MainActivity 类是:

public class MainActivity extends Activity {
ListView listView;
LinearLayout layout;
List<String> stringValues;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    layout = (LinearLayout) findViewById(R.id.progressbar_view);

    stringValues = new ArrayList<String>();

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, stringValues);

    listView.setAdapter(adapter);
    new Task().execute();
}

class Task extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected void onPreExecute() {
        layout.setVisibility(View.VISIBLE);
        listView.setVisibility(View.GONE);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        layout.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        stringValues.add("String 1");
        stringValues.add("String 2");
        stringValues.add("String 3");
        stringValues.add("String 4");
        stringValues.add("String 5");

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

这个活动会显示3秒的进度,然后会显示ListView。除了静态地将数据添加到stringValues列表之外,您还可以在doInBackground()方法中从服务器获取数据并显示它。


3
为了完整性起见:Android文档目前指出,不鼓励在进度条下面使用文本。http://developer.android.com/design/building-blocks/progress.html#activity - Dennis Stritzke

9
请使用 tutorialspoint.com 提供的示例。整个实现只需要几行代码,无需更改您的xml文件。希望这可以帮到你。
第一步:导入库
import android.app.ProgressDialog;

步骤2:声明全局变量“ProgressDialog”

ProgressDialog loading = null;

步骤 3:启动新的 ProgressDialog 并使用以下属性(请注意,此示例仅涵盖基本的圆形加载栏,不包含实时进度状态)。

loading = new ProgressDialog(v.getContext());
loading.setCancelable(true);
loading.setMessage(Constant.Message.AuthenticatingUser);
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);

步骤4:如果您使用AsyncTasks,则可以在onPreExecute方法中开始显示对话框。否则,只需将代码放置在按钮onClick事件的开头即可。

loading.show();

步骤5:如果您正在使用AsyncTasks,则可以通过将代码放置在onPostExecute方法中来关闭进度对话框。否则,只需在关闭按钮onClick事件之前放置代码即可。

loading.dismiss();

我用我的Nexus 5安卓手机v4.0.3进行了测试。祝你好运!


5
自 API Level O 起,ProgressDialog 已经被弃用。https://developer.android.com/reference/android/app/ProgressDialog.html - Varvara Kalinina

8

您是否正在扩展ListActivity?

如果是这样,请在您的xml中放置一个圆形进度对话框,其中包含以下行:

<ProgressBar
android:id="@android:id/empty"
...other stuff...
/>

现在,进度指示器会一直显示,直到您获取了所有的listview信息并设置了适配器。此时,它将返回到listview,并且进度条将消失。


我想在屏幕中央显示进度条圆圈。如果我添加进度条,我应该在XML中放置ListView在哪里? - Ani
按照正常的方式创建布局。我在我的一个应用程序中做了这件事情。如果我没记错的话,你可以将ListView放在一个高度和宽度都为“fill_parent”的全屏相对布局中。然后,在该相对布局的第二个子项中,将进度指示器水平和垂直居中。 - The Holo Dev
你能提供这个 XML 文件吗? - Ani
1
但是如果加载的结果为空呢? - dkneller

3
ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);

这是一个非常简单的实现目标的方法。就像 K.I.S.S.(保持简单笨拙)的方式 :D - Josiel Faleiros
2
在API 26中,此功能已被弃用。 - Nithin

2
在drawable文件夹下新建一个xml文件,可以随意命名(比如progressBar.xml),并在color.xml中添加<color name="silverGrey">#C0C0C0</color>
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="720" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="6"
        android:useLevel="false" >
        <size
            android:height="200dip"
            android:width="300dip" />

        <gradient
            android:angle="0"
            android:endColor="@color/silverGrey"
            android:startColor="@android:color/transparent"
            android:type="sweep"
            android:useLevel="false" />

    </shape>
</rotate>

现在,在您的XML文件中,您需要添加以下代码到listView所在的位置:
 <ListView
            android:id="@+id/list_form_statusMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>

        <ProgressBar
            android:id="@+id/progressBar"
            style="@style/CustomAlertDialogStyle"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_centerInParent="true"
            android:layout_gravity="center_horizontal"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/circularprogress"
            android:visibility="gone"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>

在AsyncTask中的方法:

@Override
protected void onPreExecute()
{
    progressbar_view.setVisibility(View.VISIBLE);

    // your code
}

在onPostExecute方法中:

@Override
protected void onPostExecute(String s)
{
    progressbar_view.setVisibility(View.GONE);

    //your code
}

0

在按钮的 onClick 选项中使用此代码或根据您的需求进行调整。

final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        progressDialog.dismiss();
    }
}).start();

0

我建议在使用listview或recyclerview时,使用SwipeRefreshLayout。像这样

    <android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/card_recycler_view"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</android.support.v4.widget.SwipeRefreshLayout>

只需在您的视图中进行包装,这样加载数据时或者通过向下滑动屏幕时,就会创建一个刷新的动画效果,就像许多应用程序中所能做的那样。
以下是如何使用它的文档:
https://developer.android.com/training/swipe/add-swipe-interface.html https://developer.android.com/training/swipe/respond-refresh-request.html

愉快的编码!


0

您可以将 ProgressBar 添加到 ListView 的页脚:

private ListView listview;
private ProgressBar progressBar;

...

progressBar = (ProgressBar) LayoutInflater.from(this).inflate(R.layout.progress_bar, null);

listview.addFooterView(progressBar);

layout/progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"
     />

当数据加载到适配器视图时,请调用:
        listview.removeFooterView(progressBar);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接