Visualización de filas vacías en Android listview
Así que me pregunto cómo hacer para llenar un ListView
con filas vacías. El ListView
se rellena a través de SQLite
db, por ejemplo, por ejemplo, sólo hay 3 elementos en la lista que quiero llenar el resto de la pantalla con filas vacías. Aquí hay una captura de pantalla de lo que quiero decir. Sí sé que es de iPhone pero demuestra lo que quiero decir:
- Descifrado AES en Android demasiado lento para ser utilizable. ¿NDK será más rápido? ¿Otras ideas?
- NullPointerException intentando acceder a un recurso de cadena
- Qué es stringentity en android y su uso
- Enviar datos (ArrayList) de Actividad a Fragmento
- Android buena arquitectura
- Actualizar el complemento de Android Studio Gradle a la última versión
- Clone textview para anexarlo a un ViewGroup
- La aplicación para Android no se bloquea, pero no responde con excepciones no detectadas
- Android Studio w / gradle: El paquete r no existe
- Error: archivos duplicados durante el empaquetado de APK Android Studio Error
- Problema básico de Java / Eclipse: las bibliotecas estándar no se pueden importar en el proyecto de Android
- android.util.Base64 codificar / decodificar indicadores parámetro
- No se puede implementar Parcelable porque no puedo hacer que el campo CREATOR esté estático
Otros lo han eludido, pero pensé que podría ayudar a publicar un fragmento de código. Si hay una mejor técnica, con mucho gusto tomaré un voto negativo si aprendo algo.
La forma barata es agregar "filas" adicionales en el xml de su diseño. Cualquier fila extra será cortada por la pantalla. Esto puede resultar desordenado: una pantalla de mayor resolución puede requerir que añada muchos TextViews adicionales. Desde que se cortan, supongo que podría agregar tantos como desee. Se vería algo como esto:
<LinearLayout> <ListView></ListView> <TextView/> <TextView/> <TextView/> ... </LinearLayout>
Otra opción es agregar filas adicionales a su ListView, como se mencionó anteriormente. Si está vinculado a una matriz, añada filas en blanco extra a la matriz y manejarla apropiadamente. Coincidentemente, si está utilizando un Cursor, puede utilizar un MaxtrixCursor & MergeCursor como se describe en esta publicación: https://stackoverflow.com/a/16440093/103131
Terminé usando una combinación de estos métodos. Intento mi mejor calcular el número de filas que quiero agregar a mi ListView, pero error en el lado de la precaución y tengo un TextViews de par en mi ListView que lo hacen todo viene junto.
Cuando se crea el Array el va a estar vinculado a la ListView sólo tiene que añadir unas cuantas filas al final de la matriz con cadenas vacías.
just make sure android:layout_height="match_parent" <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <your.app.package.CustomListView android:id="@+id/editableTourListView" android:layout_width="match_parent" android:layout_height="match_parent" > </your.app.package.CustomListView> </RelativeLayout> public class CustomListView extends ListView { private Paint mPaint = new Paint(); private Paint mPaintBackground = new Paint(); public CustomListView(Context context, AttributeSet attrs) { super(context, attrs); mPaint.setColor(Color.BLACK); mPaintBackground.setColor(Color.WHITE); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); // ListView's height final int currentHeight = getMeasuredHeight(); // this will let you know the status for the ListView, fitting/not // fitting content final int scrolledHeight = computeVerticalScrollRange(); // if (scrolledHeight >= currentHeight || scrolledHeight == 0) { // there is no need to draw something(for simplicity I assumed that // if the adapter has no items i wouldn't draw something on the // screen. If you still do want the lines then pick a decent value // to simulate a row's height and draw them until you hit the // ListView's getMeasuredHeight) // } else { final View lastChild = getChildAt(getChildCount() - 1); if(lastChild==null) return; // values used to know where to start drawing lines final int lastChildBottom = lastChild.getBottom(); // last child's height(use this to determine an appropriate value // for the row height) final int lastChildHeight = lastChild.getMeasuredHeight(); // determine the number of lines required to fill the ListView final int nrOfLines = (currentHeight - lastChildBottom) / lastChildHeight; // I used this to simulate a special color for the ListView's row background Rect r = new Rect(0, lastChildBottom, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRect(r, mPaintBackground); canvas.drawLine(0, lastChildBottom , getMeasuredWidth(), lastChildBottom, mPaint); for (int i = 0; i < nrOfLines; i++) { canvas.drawLine(0, lastChildBottom + (i + 1) * lastChildHeight, getMeasuredWidth(), lastChildBottom + (i + 1) * lastChildHeight, mPaint); } return; // } } }
El uso de una vista de texto debajo del listview parece dar la ilusión de lo que estaba buscando.
La solución de @kabir funciona. Ahora si usted es como yo (quería tener dos colores alternos en el fondo, este es su método dispached reescrito (o digamos editado)
@Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); int caseLastChildBottom = -1; int caselastChildHeight = -1; int caseNrOfLines = -1; //makes the colors follow the order (alternateColor1 - alternateColor2 - alternateColor1 - etc.) int plusIndex = 1; if (this.getChildCount() % 2 == 0) plusIndex = 0; // ListView's height final int currentHeight = getMeasuredHeight(); // this will let you know the status for the ListView, fitting/not fitting content final int scrolledHeight = computeVerticalScrollRange(); //empty listview (no item) if (scrolledHeight == 0) { //no childs exist so we take the top caseLastChildBottom = 0; //last child doesn't exist, so we set a default height (took the value in dp in the item row's height) caselastChildHeight = convertDpToPx(DEFAULT_CHILD_ROW_S_HEIGHT); // determine the number of lines required to fill the ListView caseNrOfLines = currentHeight / caselastChildHeight; } //there is a remaining gap to fill else { final View lastChild = getChildAt(getChildCount() - 1); if (lastChild == null) return; // values used to know where to start drawing lines caseLastChildBottom = lastChild.getBottom(); // last child's height(use this to determine an appropriate value for the row height) caselastChildHeight = lastChild.getMeasuredHeight(); // determine the number of lines required to fill the ListView caseNrOfLines = (currentHeight - caseLastChildBottom) / caselastChildHeight; } // values used to know where to start drawing lines final int lastChildBottom = caseLastChildBottom; // last child's height(use this to determine an appropriate value for the row height) final int lastChildHeight = caselastChildHeight; // determine the number of lines required to fill the ListView final int nrOfLines = caseNrOfLines; int i = 0; for (i = 0; i < nrOfLines; i++) { Rect r = new Rect(0, lastChildBottom + i * lastChildHeight, getMeasuredWidth(), lastChildBottom + (i + 1) * lastChildHeight); canvas.drawRect(r, (i + plusIndex) % 2 == 0 ? alternateColorView1 : alternateColorView2); } //is there a gap at the bottom of the list if(currentHeight - (nrOfLines *lastChildHeight) > 0){ Rect r = new Rect(0, lastChildBottom + i * lastChildHeight,getMeasuredWidth(), currentHeight); canvas.drawRect(r, (i + plusIndex) % 2 == 0 ? alternateColorView1 : alternateColorView2); } return; }
Olvidé estos dos colores de Paint (tal como @kabir declaró los colores):
alternateColorView1.setColor(....); alternateColorView1.setStyle(Paint.Style.FILL); alternateColorView2.setColor(....); alternateColorView2.setStyle(Paint.Style.FILL);