需求:点击列表布局 1 中的Item 自动让布局 2 滚动到顶部
Gif 先欠着
核心内容:
public int[] getLocation(View v) {
int[] loc = new int[4];
int[] location = new int[2];
v.getLocationOnScreen(location);
loc[0] = location[0];
loc[1] = location[1];
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(w, h);
loc[2] = v.getWidth();
loc[3] = v.getHeight();
return loc;
}
在RecyclerView的item点击事件中调用:
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ToastUtil.show("test");
// scrollView.scrollTo(0,500);
int[] location = getLocation(textView);//textView 替换成你的 停留在顶部的ItemView的ID
scrollView.smoothScrollBy(0, location[1] - location[3]);
}
注意事项: v.getWidth() 和v.getHeight() 这两个方法必须在页面显示出来之后调用才会有值,不过我们这是Item点击事件 不用担心 获取不到值的问题。
下面是xml文件