android scrollto 在 onResume 方法中不起作用

标签 android scrollview

我想在显示屏幕时将屏幕滚动到特定位置,所以我在 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/

相关文章:

android - 实现全局 LruCache 与许多本地 LruCache

java - 如何从数据库 Arraylist 在 Google map 上添加标记

android - ScrollView 中的 XYPlot(AndroidPlot 库)没有出现

android - alignparentbottom 用于 ScrollView 中的相对布局

Android TimePicker(轮式)无法正确响应 ScrollView 中的轻弹手势

webview - react native : Is it possible to have the height of a html content in a webview?

java - WebView cookie 不起作用

java - 使用id查找元素获取信息并添加到数组android java

android - Vimeo 嵌入 Phonegap + Android 4.2

react-native - 在 android 上响应 native ScrollView 。滚动时子项与边框半径重叠