xml中的ExpandableListView定义

Ale*_*kov 6 android

我需要手动在xml文件中定义ExpandableListView的结构.这样做是否有任何指南或示例?

谢谢

lic*_*rna 7

我两天前碰到了这个.这是我的解决方案:

首先扩展ExpandableListActivity并覆盖onCreate()方法,如下所示:

public class ExpandableExample extends ExpandableListActivity {
    @Override
    public void onCreate() {
        super.onCreate(savedInstanceState);
        setListAdapter(new BaseExpandableListAdapterExample());
    }
}
Run Code Online (Sandbox Code Playgroud)

定义BaseExpanableListAdapterExample是(内部类ExpandableExample):

protected class BaseExpandableListAdapterExample extends BaseExpandableListAdapter {
}
Run Code Online (Sandbox Code Playgroud)

然后你需要实现getChildViewgetGroupView.我做的是:

public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    View groupRow = getLayoutInflater().inflate(R.layout.group_row, null);
    TextView textView = (TextView) groupRow.findViewById(R.id.text_group);
    textView.setText(getGroup(groupPosition).toString());
    return groupRow;
}

public View getChildView(int groupPosition, int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {
    View childRow = getLayoutInflater().inflate(R.layout.child_row, null);
    TextView textView = (TextView) childRow.findViewById(R.id.text_child);
    textView.setText(getChild(groupPosition, childPosition).toString());
    return childRow;
}
Run Code Online (Sandbox Code Playgroud)

然后,你需要同时定义group_row.xmlchild_row.xml/res/layout/目录中.例如,我group_row.xml的如下:

<?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" >
    <TextView
        android:id="@+id/text_element"
        android:layout_width="fill_parent"
        android:layout_height="48dip"
        android:textSize="20sp"
        android:textColor="#fff"
        android:layout_marginLeft="48dip"
        android:gravity="center_vertical" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.如果您有任何疑问,请评论.