DmRomantsov的回答是滚动到第12个按钮的正确方法。然而,getLeft()
和getRight()
方法返回0
,因为布局尚未显示在屏幕上。现在计算布局父级和子项的宽度还为时过早。要实现它,你需要在onWindowFocusChanged
内部执行自动滚动。
@Override
public void onWindowFocusChanged(boolean hasFocus){
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
}
}
然而,在 Fragment 中,上面的方法将不起作用。我只是写了这个来给一个提示,让大家理解这个概念。为了在 Fragment 中具有相同的行为,你只需要使用一个 Runnable
来给你的 UI 显示时间。然后,使用一个水平定向的 LinearLayout
:
HorizontalScrollView mHS;
LinearLayout mLL;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_container, container, false);
mHS = (HorizontalScrollView)view.findViewById(R.id.hscrollview);
mLL = (LinearLayout)view.findViewById(R.id.hscrollview_container);
view.post(new Runnable() {
@Override
public void run() {
Log.v("","Left position of 12th child = "+mLL.getChildAt(11).getLeft());
mHS.smoothScrollTo(mLL.getChildAt(11).getLeft(), 0);
}
});
return view;
}
中间的 HorizontalScrollView:
你的问题是要自动滚动到第 12 个子元素。然而,在下面的评论中,你要求我在 HorizontalScrollView
的中间自动滚动,我假设在每台设备上都需要这样做。你需要计算屏幕的宽度、容器的总宽度以及在设备宽度内显示了多少个子元素。以下是一个简单的代码:
view.post(new Runnable() {
@Override
public void run() {
DisplayMetrics metrics = getActivity().getResources()
.getDisplayMetrics();
int widthScreen = metrics.widthPixels;
Log.v("","Width screen total = " + widthScreen);
int widthContainer = mLL.getWidth();
Log.v("","Width container total = " + widthContainer );
int widthChild = mLL.getChildAt(0).getWidth();
Log.v("","Width child = " + widthChild);
int nbChildInScreen = widthScreen / widthChild;
Log.v("","Width screen total / Width child = " + nbChildInScreen);
int positionLeftWidth = (widthContainer
- (widthChild * nbChildInScreen))/2;
Log.v("","Position left to the middle = " + positionLeftWidth);
mHS.smoothScrollTo(positionLeftWidth, 0);
}
});
带有选定值的中间HorizontalScrollView:
我有一些误解真正的需求。实际上,您想要自动滚动到选定的子视图,并将该视图显示在屏幕中间。
然后,我修改了最后一个int
positionLeftWidth
,它现在指的是所选视图相对于其父视图的左侧位置,一个屏幕中包含的子项数和所选视图的一半宽度。因此,除了positionLeftWidth
之外,代码与上面相同:
int positionChildAt = mLL.getChildAt(6).getLeft();
int positionLeftWidth = positionChildAt -
( ( nbChildInScreen
* widthChild ) / 2 )
+ ( widthChild / 2 );
mHS.smoothScrollTo(positionLeftWidth, 0);
无论在getChildAt()
方法中传入什么值,以及屏幕的宽度是多少,你总能将所选择的(在你的情况下)按钮置于屏幕中央。