android scrollto在onResume方法中不起作用

时间:2013-05-19 14:38:10

标签: android scrollview

我想在屏幕显示时将屏幕滚动到特定位置,所以我在片段的Onresume函数中执行了此代码

  scrollView.post(new Runnable() {
        @Override public void run () {
            scrollView.scrollTo(0, -200);
            Log.d(TAG, "x: " + scrollView.getScrollX() + " " + "y: " + scrollView.getScrollY());
        }
    }

    );

但是滚动视图不会滚动

1 个答案:

答案 0 :(得分:2)

我在回到它时将片段滚动到上一个位置时遇到了同样的问题。 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,因为在大多数情况下 - 当活动没有保存它的状态时 - 你就是不能使用片段&# 39; s savedInstanceState(见here

2)更具体但有时更有用的方法是为显示片段后获得焦点的元素设置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   
        }
    });
}