简体   繁体   English

添加新视图时,android scrollview滚动到顶部方向

[英]android scrollview scroll to top direction when new view added

图片

In scrollview, if I add any view in middle, normally all the views below the added view scrolls downside. 在scrollview中,如果我在中间添加任何视图,通常所添加视图下方的所有视图都会向下滚动。 But I want to scroll the top views of added view to upside without disturbing the bottom views. 但是我想在不打扰底部视图的情况下将添加视图的顶视图向上滚动。 Is it possible in scrollview , please help me ? 是否可以在scrollview中,请帮帮我?

In the figure , If view 4 was added , then view 1 has to be scrolled upwards , without changing the positions of view 2 and view 3. 在图中,如果添加了视图4,则必须向上滚动视图1,而不更改视图2和视图3的位置。

您可以获取要添加的视图的高度,然后手动滚动滚动视图,即多个像素

scrollView.scrollBy(0, viewAdded.getHeight())

I've been wanting to try this question for quite some time, I finally got the chance today. 我一直想尝试这个问题很长一段时间,我今天终于有机会了。 The method is pretty simple (in fact, @dweebo already mentioned it earlier) - we move the ScrollView up as we add the view. 该方法非常简单(事实上,@ dweebo之前已经提到过) - 我们在添加视图时将ScrollView向上移动。 For getting precise (and valid) dimensions when adding, we use a ViewTreeObserver . 为了在添加时获得精确(和有效)的维度,我们使用ViewTreeObserver Here's the code you can get hints from: 以下是您可以从中获得提示的代码:

    // Getting reference to ScrollView
    final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
    // Assuming a LinearLayout container within ScrollView
    final LinearLayout parent = (LinearLayout) findViewById(R.id.parent);

    // The child we are adding
    final View view = new View(ScaleActivity.this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100);
    view.setLayoutParams(params);

    // Finally, adding the child
    parent.addView(view, 2); // at index 2

    // This is what we need for the dimensions when adding
    ViewTreeObserver viewTreeObserver = parent.getViewTreeObserver();
    viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            parent.getViewTreeObserver().removeOnPreDrawListener(this);

            scrollView.scrollBy(0, view.getHeight());
            // For smooth scrolling, run below line instead
            // scrollView.smoothScrollBy(0, view.getHeight())

            return false;
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM