看起来我无法在我的简单布局中获取或设置任何位置或滚动量:
// Relative layout - main_layout <HorizontalScrollView android:id="@+id/MenuScroll" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none" > <LinearLayout android:layout_width="wrap_content" android:layout_height="48dp" android:orientation="horizontal" android:layout_gravity="center" android:padding="0dp" > <Button android:id="@+id/button1" android:layout_width="150dp" android:layout_height="fill_parent" /> <Button android:id="@+id/button2" android:layout_width="150dp" android:layout_height="fill_parent" /> <Button android:id="@+id/button3" android:layout_width="150dp" android:layout_height="fill_parent" /> <Button android:id="@+id/button4" android:layout_width="150dp" android:layout_height="fill_parent" /> <Button android:id="@+id/button5" android:layout_width="150dp" android:layout_height="fill_parent" /> </LinearLayout> </HorizontalScrollView> // End of RelativeLayout - main_layout
我在MainActivity中想要的是获取HorizontalScrollView中任何按钮的位置并滚动到该位置.目前我无法得到左值(它始终为0),如果我尝试滚动到HorizontalScrollView,它就不会,无论x或y的值是什么.
// imports public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); final Button button3 = (Button)findViewById(R.id.button3); Rect rectf = new Rect(); button3.getLocalVisibleRect(rectf); Log.i("Left: ",String.valueOf(rectf.left)); // it is always 0 HorizontalScrollView MenuScroll = (HorizontalScrollView)findViewById(R.id.MenuScroll); // Trying to scroll to X=100 but it doesn't MenuScroll.scrollTo(100,MenuScroll.getBottom()); } }
所以,正如我所说,我无法获得按钮的左侧位置,也可以滚动到我的HorizontalScrollView中的某个X位置.这可能吗?
解决方法
(it’s always 0)
请记住,视图在onCreate方法中没有维度,因为它们在onCreate回调返回后放在屏幕上.
What I want in my MainActivity is to get the position of any button
inside the HorizontalScrollView and scroll to that position.
final HorizontalScrollView MenuScroll = (HorizontalScrollView) findViewById(R.id.MenuScroll); MenuScroll.post(new Runnable() { @Override public void run() { final Button button3 = (Button) findViewById(R.id.button3); int scrollTo = 0; final int count = ((LinearLayout) MenuScroll.getChildAt(0)) .getChildCount(); for (int i = 0; i < count; i++) { final View child = ((LinearLayout) MenuScroll.getChildAt(0)) .getChildAt(i); if (child != button3) { scrollTo += child.getWidth(); } else { break; } } MenuScroll.scrollTo(scrollTo,0); } });
另外要小心你在布局中使用的属性(我指的是layout_gravity,如果我没有弄错的话可能会导致问题).