我想在显示屏幕时将屏幕滚动到特定位置,所以我在 fragment 的 Onresume 函数中做了这段代码
scrollView.post(new Runnable() {
@Override public void run () {
scrollView.scrollTo(0, -200);
Log.d(TAG, "x: " + scrollView.getScrollX() + " " + "y: " + scrollView.getScrollY());
}
}
);
但是 ScrollView 不滚动
最佳答案
我在返回 fragment 时遇到了将 fragment 滚动到先前位置的相同问题。 onResume() 中无法滚动。我怀疑当您发布 runnable 时(正如您在问题中提到的那样),无法保证它是否会起作用。
我找到了2 种解决方案,希望对您有所帮助:
1) 更通用的方法,仍然不适用于 API 级别 <11:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate your main view
mView = inflater.inflate(R.layout.your_fragment_id, container, false);
// find your scroll view
mScrollContainer = (ScrollView) mView.findViewById(R.id.scroll_container);
// add OnLayoutChangeListener
mView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// get your X and Y to scroll to
...
mScrollContainer.scrollTo(x,y);
}
}
});
}
你应该从你自己的源(比如你自己的包)中获取 X 和 Y,因为在大多数情况下 - 当 Activity 不保存它的状态时 - 你不能使用 fragment 的 savedInstanceState(参见 here)
2) 更具体但有时更有用的方法是为显示 fragment 后获得焦点的元素设置 OnFocusChangeListener:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
mListView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// do your scrolling here
}
});
}
关于android scrollto 在 onResume 方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635834/