滚动到ListView中的特定列表项

时间:2013-06-18 05:17:15

标签: android android-listview expandablelistview

我使用ListView(适配器)制作Fake ExandableListView(适配器)。 (因为我需要更多自定义)

一个列表项包含GroupView和ChildView(默认可见性已消失)

然后我改变子视图的可见性。

public void itemClicked(int position) {
    Group group = groupData.get(position);
    Child child = childData.get(group);
    View childView = child.getChildView();
    if (group.toggleExpansion()) {
        childView.setVisibility(View.VISIBLE);
    } else {
        childView.setVisibility(View.GONE);
    }
}

它工作正常,但我需要在展开列表项时自动滚动,就像真正的ExpandableListView

一样

如何自动滚动显示孩子?

1 个答案:

答案 0 :(得分:1)

我做到了。

如果只使用smoothScrollToPosition()=>它仅显示组视图而非子视图。

所以我在ListView中添加了OnLayoutChangeListener。像这样。

private int expandedPosition;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private boolean addOnLayoutChangeListener() {

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        return false;
    }

    listView.addOnLayoutChangeListener(new OnLayoutChangeListener() {

        @Override
        public void onLayoutChange(View v, int left, int top, int right,
                int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            LogUtils.pi("onLayoutChange");
            if (expandedPosition != ListView.INVALID_POSITION) {
                listView.smoothScrollToPosition(expandedPosition);
            }
        }
    });
    return true;
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

        boolean expanded = adapter.itemClicked(position);
        if (expanded) {
            expandedPosition = position;
        } else {
            expandedPosition = ListView.INVALID_POSITION;
        }
}