¿Cómo mostrar un ProgressBar en una vista mientras realizas algún trabajo?
Tengo una vista con EditText
, Button
y ListView
. El botón onClick()
del botón analiza algún sitio (esta parte funciona bien), pero tarda algún tiempo en mostrar la información analizada en ListView
, así que quiero mostrar ProgressBar
pequeño en el lugar, donde el ListView
debería tener lugar después de un tiempo.
Así, agrego esto a mi diseño (escribo parte importante aquí):
- Cómo crear una barra de progreso horizontal personalizada
- Android Indeterminado ProgressBar no gira
- La barra de progreso horizontal no actualiza su estado
- Android dos AsyncTasks ejecución en serie o en paralelo? - El segundo es helada pero el resultado es bueno
- Mostrar barra de progreso durante la descarga
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/layout1" android:weightSum="1.0"> <EditText android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight=".86" /> <ImageButton android:layout_height="match_parent" android:layout_width="0px" android:layout_weight=".14" /> </LinearLayout> <RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent" android:layout_below="@id/layout1" android:gravity="center" android:layout_centerInParent="true" android:id="@+id/progressbar" > <ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content" style="@android:style/Widget.ProgressBar.Small" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/layout1"> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" /> </RelativeLayout> </RelativeLayout>
En el código fuente:
progressBar = (RelativeLayout) findViewById(R.id.progressbar);
Y cada vez que quiero mostrar el ProgressBar
, hago esto:
progressBar.setVisibility(View.VISIBLE);
Para inhabilitar:
progressBar.setVisibility(View.INVISIBLE);
Pero esto no funciona.
¿Cómo puedo resolver esto?
- Barra de progreso de Android en ImageView
- ¿Cómo puedo hacer una barra de progreso personalizada en la barra de acción?
- (ProgressBar) findViewById (R.id.ProgressBar) devuelve null
- Widget de ProgressBar personalizado
- Barra de progreso de Android incrustada en ui y no en diálogo
- Necesito saber cuánto bytes se ha cargado para actualizar una barra de progreso android
- ¿Por qué no está setVisibility trabajando en Android ProgressBar?
- android progressBar no actualiza el progreso view / drawable
No hay necesidad de manipular la visibilidad de su ProgressBar
. ListView
tiene una característica llamada "vista vacía" que se muestra sólo si su ListView
está vacío. Esto es lo que debe hacer para usarlo:
- Si su actividad extiende
ListActivity
, useandroid:id="@android:id/list"
para suListView
yandroid:id="@android:id/empty"
para suProgressBar
. - Si no se extiende
ListActivity
, hay un métodosetEmptyView()
de suListView
, que le permite hacer lo mismo.
El método anterior se ajusta mejor si no necesita vaciar su ListView
(por ejemplo, los datos se cargan sólo una vez, en el inicio de la actividad). Si necesita configurar los datos después de eso, es mejor usar ViewSwitcher
, que también tiene gran ventaja – le permite aplicar la animación de transición. Para obtener más información sobre ViewSwitcher
, eche un vistazo a esto .
No es necesario anidar su ProgressBar
en otro RelativeLayout
. Simplemente centrarlo en su diseño principal y ponerlo por fin para que quede en la parte superior.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> // the rest <ProgressBar android:id="@+id/progressBar" android:layout_centerInParent="true" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </RelativeLayout>
El RelativeLayout
con el ListView
es ocultar su ProgressBar
Modificar el diseño como este y ver cómo va:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/layout1" android:weightSum="1.0"> <EditText android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight=".86" /> <ImageButton android:layout_height="match_parent" android:layout_width="0px" android:layout_weight=".14" /> </LinearLayout> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/layout1"/> <RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent" android:gravity="center" android:layout_centerInParent="true" android:id="@+id/progressbar" > <ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content" style="@android:style/Widget.ProgressBar.Small" /> </RelativeLayout> </RelativeLayout>
También echa un vistazo a una de mis respuestas , para un problema algo similar.
Intente utilizar una tarea asíncrona como la mencionada anteriormente.
/** * this class performs all the work, shows dialog before the work and dismiss it after */ public class ProgressTask extends AsyncTask<String, Void, Boolean> { public ProgressTask(ListActivity activity) { this.activity = activity; dialog = new ProgressDialog(context); } /** progress dialog to show user that the backup is processing. */ private ProgressDialog dialog; /** application context. */ private ListActivity activity; protected void onPreExecute() { this.dialog.setMessage("Progress start"); this.dialog.show(); } @Override protected void onPostExecute(final Boolean success) { if (dialog.isShowing()) { dialog.dismiss(); } //do whatever with your data } protected Boolean doInBackground(final String... args) { try{ //parsing of your website here... return true; } catch (Exception e) Log.e("tag", "error", e); return false; } } }
Para aquellos, que están interesados en la respuesta.
Las etiquetas principales sólo se escriben.
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/layout1" android:weightSum="1.0" > <EditText android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight=".86" /> <ImageButton android:layout_height="match_parent" android:layout_width="0px" android:layout_weight=".14" /> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/layout1" > <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/layout1" /> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/layout1" android:gravity="center" android:visibility="gone" android:background="#DDE7E7E8" android:id="@+id/pBar" > <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" style="@android:style/Widget.ProgressBar.Small" /> </LinearLayout> </RelativeLayout>
Y el AsyncTask
:
private class Parsing extends AsyncTask<Void, Void, Void> { private LinearLayout pBar; private Parsing() { pBar = (LinearLayout) findViewById(R.id.pBar); } @Override protected Void doInBackground(Void... params) { parsingHere(); return null; } @Override protected void onPreExecute() { super.onPreExecute(); pBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); pBar.setVisibility(View.INVISIBLE); } }