滚动到滚动视图中的特定视图 [英] Scroll to a specific view in scroll view
问题描述
我在滚动视图中添加了一个滚动视图和子对象.在某些时候,我需要滚动到一个特定的视图.
I have added a scrollview and the subchilds inside the scrollview. At some point i need to scroll to a specific view.
<scrollview>
1. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
2. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
3. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
4. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
5. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
6. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
7. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
<button>
</button>
</scrollview>
以上布局是动态创建的.所以我不能在这里发布xml文件.布局创建是完全动态的.甚至线性布局内的子视图数量也可能会发生变化.
The above layout was created dynamically. so i can't have the xml file posted here. Layout creation is completely dynamic. Even the number of child view inside the linearlayout may also vary.
因此,当我单击按钮时,我需要滚动到特定视图,在这里单击按钮时,我需要滚动到线性布局4. 我尝试了scrollTo方法,但它滚动到了scrollview的顶部.
So when i click on the button i need to get scrolled to a particular view say here when i click on button i need to scroll to the linear layout 4. I tried with the scrollTo method but it scrolls to the top of the scrollview.
请提供一些建议.
推荐答案
如果我们需要滚动到的孩子不是直接孩子,则上述解决方案将不起作用
If child that we need to scroll to is not a direct child then above solutions don't work
我在项目中使用了以下解决方案,与他人共享可能会有所帮助
I have used below solution in my project, sharing it may be helpful to others
/**
* Used to scroll to the given view.
*
* @param scrollViewParent Parent ScrollView
* @param view View to which we need to scroll.
*/
private void scrollToView(final ScrollView scrollViewParent, final View view) {
// Get deepChild Offset
Point childOffset = new Point();
getDeepChildOffset(scrollViewParent, view.getParent(), view, childOffset);
// Scroll to child.
scrollViewParent.smoothScrollTo(0, childOffset.y);
}
/**
* Used to get deep child offset.
* <p/>
* 1. We need to scroll to child in scrollview, but the child may not the direct child to scrollview.
* 2. So to get correct child position to scroll, we need to iterate through all of its parent views till the main parent.
*
* @param mainParent Main Top parent.
* @param parent Parent.
* @param child Child.
* @param accumulatedOffset Accumulated Offset.
*/
private void getDeepChildOffset(final ViewGroup mainParent, final ViewParent parent, final View child, final Point accumulatedOffset) {
ViewGroup parentGroup = (ViewGroup) parent;
accumulatedOffset.x += child.getLeft();
accumulatedOffset.y += child.getTop();
if (parentGroup.equals(mainParent)) {
return;
}
getDeepChildOffset(mainParent, parentGroup.getParent(), parentGroup, accumulatedOffset);
}
这篇关于滚动到滚动视图中的特定视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!