我在NavigationView中创建了一个RecyclerView,并使用自定义的第一项作为ListView的addHeaderView()的等效项。在标题布局的底部,我放置了一个EditText,以便过滤下面的列表。
我的想法是每当EditText获得焦点时,将RecyclerView向上滚动,直到EditText成为最顶部的项。然而,如果我的项目数足够小,无法填充整个NavigationView的高度,则RecyclerView会拒绝向上滚动,因此显示头部的一部分,而不仅仅是EditText。另外一个问题是即使列表足够大,一旦我开始过滤列表项,它仍然会向下滚动。
如何强制我的RecyclerView向上滚动,即使我没有足够的项来填充我的视图高度,以便其余的标题不再露出?
以下是我试图实现的可视化效果:
当我聚焦在搜索框上时,期望的行为是:
这是我的NavigationView xml的代码片段(典型设置):
我的想法是每当EditText获得焦点时,将RecyclerView向上滚动,直到EditText成为最顶部的项。然而,如果我的项目数足够小,无法填充整个NavigationView的高度,则RecyclerView会拒绝向上滚动,因此显示头部的一部分,而不仅仅是EditText。另外一个问题是即使列表足够大,一旦我开始过滤列表项,它仍然会向下滚动。
如何强制我的RecyclerView向上滚动,即使我没有足够的项来填充我的视图高度,以便其余的标题不再露出?
以下是我试图实现的可视化效果:
_______________
| HEADER LINE 1 |
| HEADER LINE 2 |
| HEADER LINE 3 |
| ------------- |
| Search box |
| ------------- |
| List item 1 |
| List item 2 |
| List item 3 |
---------------
当我聚焦在搜索框上时,期望的行为是:
_______________
| ------------- |
| Search box | <- becomes the topmost item. I can already achieve this
| ------------- | with RecyclerView.smoothScrollBy(dx, dy)
| List item 1 | except when the list is small enough (see below)
| List item 2 |
| List item 3 |
| List item 4 |
| | <- empty space is okay and is desired if dataset
| | is small enough
---------------
实际上会发生什么:
_______________
| HEADER LINE 2 | <- the header is 'bleeding' on top
| HEADER LINE 3 |
| ------------- |
| Search box | <- search box cannot take the topmost spot
| ------------- | as the recycler tries to position itself to fill in
| List item 1 | the bottom part with items
| List item 2 |
| List item 3 |
| List item 4 | <- items are pushed down to the bottom to fill
--------------- in the space
这是我的NavigationView xml的代码片段(典型设置):
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true">
<android.support.v7.widget.RecyclerView
android:id="@+id/drawer_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.NavigationView>
这里是带有自定义标题的ViewHolder(RecyclerView适配器):
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == HEADER) {
return new HeaderHolder(mHeaderView);
} else {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ItemViewHolder(v);
}
}
抽屉标题只是我在主活动中填充的一个XML布局(我在那里分配了侦听器和动画),然后通过我创建的 setHeaderView(View header) 传递给我的RecyclerView适配器。