2015-10-15 4 views
3

У меня есть макет, который имеет два ListViews, и все они находятся внутри прокрутки, потому что содержимое может превышать высоту устройства. Вот макет:Listview в ScrollView не отображает все элементы

<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" 
    tools:context="com.galleri5.android.activities.ImageActivity"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar" 
     android:elevation="4dp" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="#FAC80A"> 

     <RelativeLayout 
      android:id="@+id/relativeLayout" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Image" 
       android:textColor="#000000" 
       android:textSize="17sp" 
       android:layout_centerVertical="true" 
       android:id="@+id/textView80" /> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/imageView134" 
       android:src="@drawable/gallery_page_ic_notifications" 
       android:layout_alignParentEnd="true" 
       android:layout_marginRight="30dp" 
       android:layout_centerVertical="true" /> 

     </RelativeLayout> 

    </android.support.v7.widget.Toolbar> 

    <ScrollView 
     android:id="@+id/scrollView2" 
     android:layout_below="@+id/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:fillViewport="true"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:background="@drawable/user_profile_bg" 
      android:orientation="vertical"> 

      <ImageView 
       android:id="@+id/imageView102" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center_horizontal" 
       android:layout_marginBottom="25dp" 
       android:layout_marginTop="10dp" 
       android:adjustViewBounds="true" /> 

      <ImageView 
       android:id="@+id/imageView103" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center_horizontal" 
       android:layout_marginBottom="25dp" 
       android:src="@drawable/user_profile_activity_1_shape_thin_line_separator" /> 

      <TextView 
       android:id="@+id/textView38" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginBottom="10dp" 
       android:layout_marginLeft="30dp" 
       android:layout_marginRight="30dp" 
       android:alpha="0.8" 
       android:inputType="textMultiLine" 
       android:textColor="#FFFFFF" /> 

      <TextView 
       android:id="@+id/textView39" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginBottom="25dp" 
       android:layout_marginLeft="30dp" 
       android:textAppearance="?android:attr/textAppearanceSmall" 
       android:textColor="#707070" /> 

      <ImageView 
       android:id="@+id/imageView104" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center_horizontal" 
       android:layout_marginBottom="25dp" 
       android:src="@drawable/user_profile_activity_1_shape_thin_line_separator" /> 

      <LinearLayout 
       android:id="@+id/linearLayout3" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginBottom="20dp" 
       android:layout_marginLeft="30dp" 
       android:layout_marginRight="30dp" 
       android:orientation="horizontal"> 

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

        <ImageView 
         android:id="@+id/imageView107" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_centerVertical="true" 
         android:paddingRight="5dp" /> 

        <LinearLayout 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_centerVertical="true" 
         android:layout_toRightOf="@+id/imageView107" 
         android:orientation="vertical" 
         android:paddingLeft="5dp"> 

         <TextView 
          android:id="@+id/textView45" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:alpha="0.8" 
          android:paddingBottom="2dp" 
          android:textColor="#FFFFFF" /> 

         <TextView 
          android:id="@+id/textView46" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:paddingTop="2dp" 
          android:textAppearance="?android:attr/textAppearanceSmall" 
          android:textColor="#707070" 
          android:textSize="12sp" /> 
        </LinearLayout> 

        <ImageView 
         android:id="@+id/imageView108" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_alignParentEnd="true" 
         android:layout_centerVertical="true" 
         android:src="@drawable/image_page_button_bookmark" /> 
       </RelativeLayout> 
      </LinearLayout> 

      <ImageView 
       android:id="@+id/imageView109" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center_horizontal" 
       android:layout_marginBottom="10dp" 
       android:src="@drawable/user_profile_activity_1_shape_thin_line_separator" /> 

      <android.support.v7.widget.CardView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginBottom="35dp" 
       android:layout_marginLeft="30dp" 
       android:layout_marginRight="30dp"> 

       <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:background="#343031" 
        android:orientation="vertical"> 

        <TextView 
         android:id="@+id/textView47" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_marginLeft="25dp" 
         android:layout_marginTop="15dp" 
         android:text="This Image is Part Of..." 
         android:textColor="#707070" /> 

        <ImageView 
         android:id="@+id/imageView110" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_gravity="center_horizontal" 
         android:layout_marginBottom="20dp" 
         android:layout_marginTop="10dp" 
         android:src="@drawable/user_profile_activity_1_shape_thin_line_separator" /> 

        <ListView 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:id="@+id/listView2" /> 

        <TextView 
         android:id="@+id/textView57" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_marginBottom="20dp" 
         android:layout_marginLeft="30dp" 
         android:text="See All Galleries" 
         android:textColor="#707070" /> 

       </LinearLayout> 


      </android.support.v7.widget.CardView> 

      <ImageView 
       android:id="@+id/imageView125" 
       android:layout_width="305dp" 
       android:layout_height="wrap_content" 
       android:layout_gravity="right" 
       android:layout_marginBottom="20dp" 
       android:src="@drawable/image_page_belongs_to_shape_line_separator_1" /> 

      <ListView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/listView6" /> 

      <EditText 
       android:id="@+id/editText6" 
       android:layout_width="300dp" 
       android:layout_height="wrap_content" 
       android:layout_marginLeft="40dp" 
       android:alpha="0.8" 
       android:inputType="text" 
       android:elegantTextHeight="true" 
       android:enabled="true" 
       android:hint="Comment" 
       android:textCursorDrawable="@null" 
       android:textColor="#FFFFFF" 
       android:textColorHint="#FFFFFF" 
       android:layout_marginTop="10dp" 
       android:backgroundTint="#fac80a" /> 

     </LinearLayout> 
    </ScrollView> 

</RelativeLayout> 

В двух списках есть id listView2 и listView6. Я правильно настроил адаптеры для обоих списков. Я получаю данные от бэкэнд. Для обоих списков я получаю два элемента из бэкэнд, но на самом деле он показывает только один элемент в каждом списке. Я также пытаюсь добавить элемент во второй listView, используя notifyDataSetChanged(), но это тоже не работает. Я получаю только один предмет. Какая может быть причина и как ее исправить?

+0

ListView может прокручивать себя, когда вы используете его в Scrollview это может вызвать проблемы – Pirisok

+0

Выбора заключается в использовании вида авто списка расшириться его высоту дочернего элемента. Таким образом, вы сможете использовать scrollview, а высота представления списка будет равна его высоте ребенка, поэтому прокрутка не потребуется. Вот ссылка 2-го ответа DougW [link] (http://stackoverflow.com/questions/3495890/how-can-i-put-a-listview-into-a-scrollview-without-it-collapsing) ... другой вариант - использовать NestedScroll с Recyclerview. Например, мне нужно будет найти или написать его и сообщить вам. –

+0

Мое предложение - использовать [RecyclerView] (https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html) с несколькими типами просмотров. Посмотрите на следующий [gist] (https://gist.github.com/hister/d56c00fb5fd2dfaf279b). –

ответ

1

Вот что я сделал, в случае, если кто-то другой, имеющий подобную проблему:

Примечание: Это решение очень неэффективно. Я использую его, потому что у меня есть не более двух элементов в моем спискеView. Я бы не рекомендовал его другим, если у вас есть listView, у которого есть значительное количество элементов.

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

      int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom(); 
      for (int i = 0; i < listAdapter.getCount(); i++) { 
       View listItem = listAdapter.getView(i, null, listView); 
       if (listItem instanceof ViewGroup) { 
        listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
       } 
       listItem.measure(0, 0); 
       totalHeight += listItem.getMeasuredHeight(); 
      } 

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

Я вызвал эту функцию в обоих списках после настройки адаптера. Надеюсь, это поможет.

+0

вы понятия не имеете, как неправильно ваше решение .. он может легко вызвать так много проблем, связанных с процессором, памятью и т. Д. что делать, если у вас есть 1000 элементов в этом списке? вы загружаете список для загрузки 1000 элементов? это так неправильно. – JozeRi

+0

Я знаю, что этот метод не очень эффективен. Но я показываю только 2 элемента в списке при макс. Поэтому я продолжил этот метод. –

+0

Возможно, вы лично используете 2 предмета при макс .. но вы сами написали это: «Вот что я сделал, на случай, если у кого-то другая проблема». Другие могут использовать этот код и полагаться на него. и у тех других может быть более 2-х предметов (возможно, намного больше, чем 2), и они могут подумать, что этот код является хорошим решением, но я не думаю, что это так. пожалуйста, по крайней мере отредактируйте свой ответ, чтобы другие кодеры не запутались. ty :) – JozeRi

0

Не рекомендуется иметь список в прокрутке. Хотя в списке показаны все элементы, прокрутка в списке не будет хорошей. Чтобы избежать этой ситуации, вы должны перестроить макет.

Надеюсь, это поможет вам!

+0

Прямо сейчас, содержание моих списков занимает около 30% высоты нижнего экрана. Если я не создам scrollview, я смогу прокрутить только нижние 30% экрана. Я хочу, чтобы содержимое над списком также прокручивалось, если содержимое объединило высоту, большую, чем у устройства. –

+0

Я вас понимаю, Можете ли вы изменить свою логику экрана? Например, покажите список в диалоговом окне или на новом экране, когда вы нажали кнопку типа «показать список» ... –

+0

Я не могу. Это было сделано дизайнером, и я должен это реализовать. Я также пробовал вложенный просмотр прокрутки, но это тоже не работает. –

1

Как я сказал в комментарии вместо использования listview внутри scrollview, используйте recyclerview. Я только что создал demo project, чтобы вы поняли о переработке с несколькими макетами. Импортируйте проект и посмотрите на это.

Точно так же вы обрезаете текущий макет в несколько макетов и раздуваете их на основе ваших потребностей и реализуете его в режиме recyclerview.

1

Другой возможностью было бы использовать один ListView и 2- .. различные адаптеры и много различных Просмотров. А для ListViews - https://github.com/commonsguy/cwac-merge. Добавляет много адаптеров и представлений в один большой адаптер, который можно добавить в 1 ListView.

Текст со страницы:

Просто создайте MergeAdapter и вызовите addAdapter(), addView(), или addViews() (последний прием списка), а затем подключить адаптер к ListView.

Gradle:

repositories { 
    maven { 
     url "https://s3.amazonaws.com/repo.commonsware.com" 
    } 
} 

dependencies { 
    compile 'com.commonsware.cwac:merge:1.1.+' 
} 
+0

Можете ли вы привести пример для меня? –

Смежные вопросы