安卓scrollto不能在onResume方法工作 [英] android scrollto does not work in onResume method

查看:271
本文介绍了安卓scrollto不能在onResume方法工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想滚动屏幕上的特定位置时,屏幕显示,所以我在我的片段Onresume功能,这样做code

I would like to scroll a screen to a particular position when the screen is displayed so i did this code in Onresume function of my fragment

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

    );

但滚动视图没有按'T滚动

but the scrollview doesn 't scroll

推荐答案

我遇到了同样的问题,当返回到它的滚动片段到previous位置。没有滚动可能在onResume()。当您发布可运行(如你提到你的问题),也不能保证它是否会工作,我怀疑。

我发现的 2的解决方案,希望这有助于:

1)更多通用的方法,它仍然没有为API级别&LT工作; 11:

I've encountered the same problem with scrolling fragment to the previous position when returning to it. No scrolling possible in onResume(). I suspect when you post runnable (as you mention in your question) there is no guarantee whether it will work.

I've found 2 solutions, hope this helps:

1) More general approach, still it doesn't work for API level < 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从自己的源代码(说自己的包),因为在大多数情况下 - 活动时不保存其状态 - 你只是不能使用片段的savedInstanceState(见<一href="http://developer.android.com/reference/android/support/v4/app/Fragment.html#onSaveInstanceState(android.os.Bundle)"相对=nofollow>这里)

You should get X and Y from your own source (say your own bundle), since in most cases - when activity doesn't save it's state - you just can't use fragment's savedInstanceState (see here)

2)更具体的,但有时比较有用的方法是设置OnFocusChangeListener为获得焦点的片段显示在元素:

2) More specific but sometimes more useful method is to set OnFocusChangeListener for the element that gets focus after fragment is shown:

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   
        }
    });
}

这篇关于安卓scrollto不能在onResume方法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆