Android cómo mostrar 2 vistas de lista en una actividad una tras otra


He usado este código para mostrar 2 vistas de lista una encima de la otra.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="#f00" >
</ListView>

<ListView
    android:id="@+id/listView2"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="#0f0" >
</ListView>

El problema es que, esto hace que las 2 vistas de lista ocupen la mitad de la pantalla. Estoy agregando un encabezado a ambas listas como este.

LevelAdapter adapter = new LevelAdapter(getActivity(),
            R.layout.list_item, weather_data);

    View header = inflater.inflate(R.layout.header2, null);
    View header2 = inflater.inflate(R.layout.header, null);
   lv1.addHeaderView(header);
   lv2.addHeaderView(header2);
    lv1.setAdapter(adapter);
    lv2.setAdapter(adapter);

Me gustaría que el encabezado de la segunda lista aparezca después de que la primera lista haya terminado. ¿Cómo hago esto?¿Cómo hago que las vistas de lista aparezcan de tal manera que la segunda comience cuando la primera haya terminado ? Gracias

Author: S H, 2013-07-17

9 answers

Use así:

Eliminar el diseño lineal. utilice el diseño relativo y dentro de eso coloque sus dos vistas de lista como esta.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/scrollojt"
android:fillViewport="true" >

   <RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f00" >
 </ListView>

 <ListView
android:id="@+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/listView1"
android:background="#0f0" >
</ListView>
    </RelativeLayout>
  </ScrollView>

Añadir Utilidad.java

public class Utility {

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}

En su Actividad:

 lv1.setAdapter(adapter);
 lv2.setAdapter(adapter);

Utility.setListViewHeightBasedOnChildren(lv1);
Utility.setListViewHeightBasedOnChildren(lv2);
 41
Author: Nirmal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 07:58:03

Antes de desplazarse

Activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dip" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:text="ANDROID" />

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:background="#B29090" >
        </ListView>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:gravity="center_vertical"
            android:text="IOS" />

        <ListView
            android:id="@+id/listView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:background="#4A9C67" >
        </ListView>
    </LinearLayout>

</ScrollView>

MainActivity.java

package com.example.listviewin1xmldemo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

    private ListView mListView1, mListView2;

    private String [] data1 ={"Hiren", "Pratik", "Dhruv", "Narendra", "Piyush", "Priyank"};
    private String [] data2 ={"Kirit", "Miral", "Bhushan", "Jiten", "Ajay", "Kamlesh"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView1 = (ListView)findViewById(R.id.listView1);
        mListView2 = (ListView)findViewById(R.id.listView2);

        mListView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1));
        mListView2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data2));

        ListUtils.setDynamicHeight(mListView1);
        ListUtils.setDynamicHeight(mListView2);
    }


    public static class ListUtils {
        public static void setDynamicHeight(ListView mListView) {
            ListAdapter mListAdapter = mListView.getAdapter();
            if (mListAdapter == null) {
                // when adapter is null
                return;
            }
            int height = 0;
            int desiredWidth = MeasureSpec.makeMeasureSpec(mListView.getWidth(), MeasureSpec.UNSPECIFIED);
            for (int i = 0; i < mListAdapter.getCount(); i++) {
                View listItem = mListAdapter.getView(i, null, mListView);
                listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
                height += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = mListView.getLayoutParams();
            params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
            mListView.setLayoutParams(params);
            mListView.requestLayout();
        }
    }
}
 94
Author: Hiren Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-14 05:59:26

Debe usar ExpandableListView (http://developer.android.com/reference/android/widget/ExpandableListView.html ). Tendría dos secciones en lugar de dos vistas de lista, pero (incluidas las cabeceras) se alinearán como se describió.

 9
Author: boro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-19 12:34:03

No es una buena práctica utilizar más de un ListViews' en un solo contenedor. Causa problemas de medición y rendimiento. Mejor es usar una sola vista de lista con varios tipos de vista. En el caso de los tipos de vista podría ser: listview1_viewtype, listview2_viewtype, listview2_header_viewtype. Para el encabezado de first ListView puede usar solo encabezado.

 5
Author: Kirill Boyarshinov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:25

Pruebe con ScrollView y LinearLayout:

Activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
   <ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/action_bar1"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dip">

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="200dip"
            android:layout_margin="10dip"
            android:background="#B29090">
        </ListView>



        <ListView
            android:id="@+id/listview2"
            android:layout_width="match_parent"
            android:layout_height="200dip"
            android:layout_margin="10dip"
            android:background="#4A9C67">
        </ListView>
    </LinearLayout>
</ScrollView>
</RelativeLayout>

MainActivity.java

 private ListView list1, list2;
private String [] data1 ={"H", "P", "D", "N", "P", "P"};
private String [] data2 ={"K", "M", "B", "K", "A", "K"};
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sounds);
    list1 = (ListView) findViewById(R.id.listView1);
    list2 = (ListView) findViewById(R.id.listview2);

    list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data1));
    list2.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data2));



}
 3
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-10 10:49:01

Cuando se proporcionan pesos, la altura debe proporcionarse como 0dp o wrap_content. pero no lo estás haciendo. cambie su archivo xml como se muestra a continuación. Espero que funcione para ti.

Según su comentario estoy editando mi publicación de acuerdo con el requisito Solución

1 -: Crear una vista de lista con solo 2 filas

1.1 -: Agregar una vista de lista como una fila hija en first listview #1

1.2 -: Agregar otra vista de lista como segunda fila hija en first listview #1

Espero que de esta manera pueda lograr éxito.

 2
Author: DynamicMind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 07:58:44

Soy nuevo en Android también y tengo algo similar (no exactamente, pero una especie de solución) pero mucho más FÁCIL, al hacer un archivo de diseño y poner el número requerido de vistas de lista en él y otro diseño XML y envolver el diseño previamente hecho en ScrollView.

Supongamos que tiene un diseño llamado two_listview_layout.xml definido como

<RelativeLayout
..>
    <ListView
        android:id="@+id/listViewOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ListView
        android:id="@+id/listViewTwo"
        android:layout_width="match_parent"
        android:layout_width="wrap_content"/>
</RelativeLayout>

RelativeLayout no es obligatorio aquí, pero puede jugar con sus requisitos y los diseños.

Ahora haga otro diseño en el que este diseño está envuelto en ScrollView. Como ScrollView solo puede tener 1 hijo directo, tendrá este diseño completo como hijo.

Nombre este diseño (abajo) como final_layout.xml

<FrameLayout
...>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <include layout="@layout/two_listview_layout" />
    </ScrollView>
</FrameLayout>

Ahora infla este final_layout.xml en tu fragment / activity y usa los ids que fueron nombrados en el two_listview_layout.xml para acceder a cualquiera de las vistas de lista.

La salida es algo como esto: (disculpas por la mala calidad de screen recorder: p) Trailers y Reseñas - ambos son listviews aquí.

introduzca la descripción de la imagen aquí

 1
Author: T.M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-09 18:22:58

Agregar layout_weight funcionó para mí.

<ListView
    android:id="@+id/excerciseListView"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:divider="#B6B6B6"
    android:dividerHeight="1sp"
    android:layout_weight="3"></ListView>
<ListView
    android:id="@+id/instructionListView"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:divider="#B6B6B6"
    android:dividerHeight="1sp" 
   android:layout_weight="1"></ListView>
 0
Author: Trideep Rath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 09:28:42

Pruebe con el diseño relativo:

<?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" >

<ListView
 android:id="@+id/listView1"
 android:layout_width="match_parent"
 android:layout_height="fill_parent"
 android:layout_weight="1"
 android:layout_below="@+id/listView1"
 android:background="#f00" >
</ListView>
<ListView
 android:id="@+id/listView2"
 android:layout_width="match_parent"
 android:layout_height="fill_parent"
 android:layout_weight="1"
 android:background="#0f0" >
</ListView>
</RelativeLayout>
 -3
Author: Slenkra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 07:29:36