ExpandableListView с ViewPager как дочерние элементы выполняет getChildView дважды - PullRequest
0 голосов
/ 09 апреля 2019

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

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

Мое лучшее предположение, что оно как-то связано со свойством высоты макетов, но как бы я его не изменял, я не смог решить проблему. Пожалуйста помоги. Я полностью потерян. Я использовал учебник для этого кода, и я, кажется, единственный, кто имеет эту проблему, судя по разделу комментариев YouTube. (https://www.youtube.com/watch?v=jZxZIFnJ9jE)

(Если вам нужна какая-либо другая часть кода, пожалуйста, дайте мне знать.)

delete.xml файл выглядит так

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

    <TextView
        android:id="@+id/suka"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="suka"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
        android:paddingStart="?android:attr/expandableListPreferredChildPaddingLeft"
        />

</LinearLayout>

sublist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp" android:background="@color/white"
    android:id="@+id/sublist">

    <TextView
        android:id="@+id/dict_entry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
        android:paddingStart="?android:attr/expandableListPreferredChildPaddingLeft"
        android:textSize="16sp"
        android:textColor="@color/colorAccent"
        android:text="test"
        />

</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@color/colorPrimary">

    <EditText
        android:id="@+id/search_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/search_hint"
        android:layout_margin="15dp"
        android:padding="5dp"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@color/white"
        android:adjustViewBounds="true"
        android:maxLines="1"
        android:inputType="text"
        android:onClick="lookup_word"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/search_bar"
        android:orientation="horizontal">

        <ExpandableListView
            android:id="@+id/search_result_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="#333"
            android:dividerHeight="1dp"
            android:background="@color/white"
            android:layout_margin="15dp"/>


     </LinearLayout>

</RelativeLayout>

ExpandableListAdapter.java

package com.lunaticcoding.linguodict;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.view.ViewPager;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;

public class ExpendableListAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<String> data;
    private HashMap<String, String[]> listHashMap;

    private LayoutInflater inflater;
    private String pageData[];

    public ExpendableListAdapter(Context context, List<String> list, HashMap<String, String[]> hashMap) {
        this.context = context;
        this.data = list;
        this.listHashMap = hashMap;
    }


    @Override
    public int getGroupCount() {
        return data.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return listHashMap.get(data.get(groupPosition)).length;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return data.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return listHashMap.get(data.get(groupPosition))[childPosition];
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.sublist, null);
        }

        TextView textView = (TextView) convertView.findViewById(R.id.dict_entry);
        textView.setText(data.get(groupPosition));
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final String childText = (String)getChild(groupPosition, childPosition);
        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.delete, null);
        }
        TextView textView = (TextView) convertView.findViewById(R.id.suka);
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

MainActivity (только OnCreate)

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

        searchBar = (EditText) findViewById(R.id.search_bar);
        searchResults = (ExpandableListView) findViewById(R.id.search_result_list);

        list_results = new ArrayList<>();
        examples_results = new HashMap<>();
        list_results.add("test1");
        list_results.add("test2");
        list_results.add("test3");

        String pageData1[] = new String[]{"si", "siiii"};
        String pageData2[] = new String[]{"jifasfa", "sfasdfasiii"};
        String pageData3[] = new String[]{"jifasfa", "sfasdfasiii"};
        examples_results.put(list_results.get(0), pageData1);
        examples_results.put(list_results.get(1), pageData2);
        examples_results.put(list_results.get(2), pageData3);

        searchResultsAdapter = new ExpendableListAdapter(this, list_results, examples_results);
        searchResults.setAdapter(searchResultsAdapter);

        lastExpandedPosition = -1;
        searchResults.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                if(lastExpandedPosition != -1 && (lastExpandedPosition != groupPosition)){
                    searchResults.collapseGroup(lastExpandedPosition);
                }
                lastExpandedPosition = groupPosition;
            }
        });

    }

1 Ответ

0 голосов
/ 10 апреля 2019

В sub_list.xml layout_height равен "wrap_content".Измените его на фиксированную высоту (несколько dp) или match_parent, и он будет работать.

Причина: wrap_content должен вычислить высоту содержимого макета, которому он должен соответствовать, перезагружая макет впоследствии -> создавая список большечем один раз.

...