【问题标题】:ExpandableListView in Fragment Issue片段问题中的 ExpandableListView
【发布时间】:2014-07-27 20:17:06
【问题描述】:

我正在尝试在片段中实现可扩展列表视图。没有错误出现,当我尝试记录 List<String>HashMap<String, List<String>> 的输出时,我得到了记录的实际数据。

我遇到的问题是当我在片段中显示实际的可扩展列表视图时。仅显示列表的第一项,我无法展开它(如下图所示):

.

这是我正在使用的代码:

片段类

public static class LineupFragment extends Fragment {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_lineup, null);

        expListView = (ExpandableListView) rootView.findViewById(R.id.expListView);

        prepareListData();

        listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
        expListView.setAdapter(listAdapter);

        Log.i("groups", listDataHeader.toString());
        Log.i("details", listDataChild.toString());

        // Listview Group click listener
        expListView.setOnGroupClickListener(new OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // Listview Group expanded listener
        expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getActivity().getApplicationContext(),listDataHeader.get(groupPosition) + " Expanded",Toast.LENGTH_SHORT).show();
            }
        });

        // Listview Group collasped listener
        expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getActivity().getApplicationContext(),listDataHeader.get(groupPosition) + " Collapsed",Toast.LENGTH_SHORT).show();
            }
        });

        // Listview on child click listener
        expListView.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
                Toast.makeText(getActivity().getApplicationContext(),listDataHeader.get(groupPosition) + " : " + listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition), Toast.LENGTH_SHORT).show();
                return false;
            }
        });   
    return rootView;
    }

    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding child data
        listDataHeader.add("Top 250");
        listDataHeader.add("Now Showing");
        listDataHeader.add("Coming Soon..");

        // Adding child data
        List<String> top250 = new ArrayList<String>();
        top250.add("The Shawshank Redemption");
        top250.add("The Godfather");
        top250.add("The Godfather: Part II");
        top250.add("Pulp Fiction");
        top250.add("The Good, the Bad and the Ugly");
        top250.add("The Dark Knight");
        top250.add("12 Angry Men");

        List<String> nowShowing = new ArrayList<String>();
        nowShowing.add("The Conjuring Despicable Me TurboGrown Ups 2 Red 2 the Wolverine The Conjuring Despicable Me TurboGrown Ups 2 Red 2 the Wolverine");

        List<String> comingSoon = new ArrayList<String>();
        comingSoon.add("2 Guns");
        comingSoon.add("The Smurfs 2");
        comingSoon.add("The Spectacular Now");
        comingSoon.add("The Canyons");
        comingSoon.add("Europa Report");

        listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
        listDataChild.put(listDataHeader.get(1), nowShowing);
        listDataChild.put(listDataHeader.get(2), comingSoon);

    }

**Adapter class**

    public class ExpandableListAdapter extends BaseExpandableListAdapter {

                private Activity _context;
                private List<String> _listDataHeader; // header titles
                // child data in format of header title, child title
                private HashMap<String, List<String>> _listDataChild;

                public ExpandableListAdapter(Activity context, List<String> listDataHeader,
                        HashMap<String, List<String>> listChildData) {
                    this._context = context;
                    this._listDataHeader = listDataHeader;
                    this._listDataChild = listChildData;
                }

                @Override
                public Object getChild(int groupPosition, int childPosititon) {
                    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                            .get(childPosititon);
                }

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

                @Override
                public View getChildView(int groupPosition, final int childPosition,
                        boolean isLastChild, View convertView, ViewGroup parent) {

                    final String childText = (String) getChild(groupPosition, childPosition);

                    if (convertView == null) {
                        LayoutInflater infalInflater = (LayoutInflater) this._context
                                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        convertView = infalInflater.inflate(R.layout.list_item, null);
                    }

                    TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);

                    txtListChild.setText(childText);
                    return convertView;
                }

                @Override
                public int getChildrenCount(int groupPosition) {
                    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                            .size();
                }

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

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

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

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

                    TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
                    lblListHeader.setTypeface(null, Typeface.BOLD);
                    lblListHeader.setText(headerTitle);

                    return convertView;
                }

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

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

编辑:这是 fragment_lineup.xml 文件的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_black"
    android:orientation="vertical" >

    <ExpandableListView
        android:id="@+id/expListView"
        android:layout_width="match_parent"
        android:layout_height="310dp"
        android:layout_weight="0.14" >
    </ExpandableListView>

</LinearLayout>

然后我还有另外两个用于自定义布局的 lavout 文件。

**list_group.xml**

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_black"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="52dp"
        android:layout_height="52dp"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/photo"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/app_name"
            android:fitsSystemWindows="true" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="52dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/lblListHeader"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:paddingLeft="6dip"
            android:paddingTop="6dip"
            android:textColor="#CC0000"
            android:textSize="20dp"
            android:textStyle="bold"
            tools:ignore="SpUsage" />

    </LinearLayout>

</LinearLayout>

另一个为**list_item.xml**

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

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:paddingBottom="5dp"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
        android:paddingTop="5dp"
        android:textSize="13sp" />

</LinearLayout>

请注意,我需要使用片段,因为此类是我正在开发的更大应用程序的一部分,并且使用选项卡。整个代码在活动中运行良好。

我怀疑我的问题出在适配器类中。

【问题讨论】:

  • 可以发一下片段的布局吗? 整个代码在活动中运行良好。 - 这究竟意味着什么?哪个部分有效?
  • 以上所有代码在一个活动中都能完美运行,但在片段中却不行
  • 如我所说,贴出fragment的布局,一眼看去,适配器类似乎没有什么问题。
  • 你试过滚动可见元素吗?它可以滚动吗?
  • 不,它不可滚动。仅显示该元素。它应该总共显示 4 个元素。

标签: android android-fragments expandablelistview


【解决方案1】:

我终于知道这是怎么做到的了。我正在为遇到相同问题的任何人粘贴下面的代码。随意使用:

public static class LineupFragment extends Fragment {

View rootView;
ExpandableListView lv;
private String[] groups;
private String[][] children;


public LineupFragment() {

}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    groups = new String[] { "Test Header 1", "Test Header 2", "Test Header 3", "Test Header 4" };

    children = new String [][] {
        { "s simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." },
        { "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of comes from a line in section 1.10.32." },
        { "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)." },
        { "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc." }
    };
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_lineup, container, false);  

return rootView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    lv = (ExpandableListView) view.findViewById(R.id.expListView);
    lv.setAdapter(new ExpandableListAdapter(groups, children));
    lv.setGroupIndicator(null);

}

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private final LayoutInflater inf;
    private String[] groups;
    private String[][] children;

    public ExpandableListAdapter(String[] groups, String[][] children) {
        this.groups = groups;
        this.children = children;
        inf = LayoutInflater.from(getActivity());
    }

    @Override
    public int getGroupCount() {
        return groups.length;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return children[groupPosition].length;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groups[groupPosition];
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return children[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 getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

         ViewHolder holder;
            if (convertView == null) {
                convertView = inf.inflate(R.layout.list_item, parent, false);
                holder = new ViewHolder();

                holder.text = (TextView) convertView.findViewById(R.id.lblListItem);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(getChild(groupPosition, childPosition).toString());

            return convertView;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = inf.inflate(R.layout.list_group, parent, false);

            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.lblListHeader);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.text.setText(getGroup(groupPosition).toString());

        return convertView;
    }

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

    private class ViewHolder {
        TextView text;
    }
}

这就是新布局现在的样子:

随意在你的代码中使用它,希望我能以某种方式帮助你:)

【讨论】:

  • 我遇到了同样的问题......你似乎已经解决了,但你的答案中没有任何解释是什么原因以及你如何解决它......你能解释一下你的答案吗? ..
  • 如果我没记错的话,基本上我所做的就是将 xml 中的 textview 设置为 textview 中的 match_parent。因此第一个元素占据了整个屏幕。
  • 但是你为什么不使用hashmap...hashmap比多维数组更高效更简单..
  • 解决了我的烦恼。谢谢。
  • 我认为您的问题是您尚未创建 xml 文件。从您提到的错误来看,您似乎还没有在布局文件中创建小部件。查看以下包含您需要的布局 xml 文件的链接:dropbox.com/s/vaf36sytbg03dvm/fragment_lineup.xml?dl=0dropbox.com/s/90bc52f7mpabpc5/list_item.xml?dl=0dropbox.com/s/pi76alb4o2k7lvo/list_group.xml?dl=0
【解决方案2】:

Dev.mi 的解决方案运行良好。但是由于一些愚蠢的错误,我陷入了类似的问题。我正在做一些复杂的设计,并使用 scrollView 作为 ExpandableListView 的根父级。

在线性布局中带有 wrapcontent 的 ExpandableListView 足以使其可滚动。

在外面添加 Scrollable View 会导致 Expandable ListView 缩小到只显示一个标题。

不要将 ExpandableListView 放在 Scroll View 中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2015-10-04
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多