Android TabHost Auto Scroll vertically in side ScrollView on TabChange?

不想你离开。 提交于 2019-12-19 05:07:09

问题


I am using TabHost inside ScrollView in my Activity but when ever I select tab it automatically scrolls my view vertically to end.


回答1:


In this case child view getting focus due to that it get scrolled upward.

for resolve this you need to create custom ScrollView that extend ScrollView. code snipt will look like this.

public class MyScrollView extends ScrollView {


    public MyScrollView(Context context) {
        super(context);

    }



    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }


    @Override
    public void requestChildFocus(View child, View focused) {
       // if (focused instanceof TabHost)   // here 
            return;
        //super.requestChildFocus(child, focused);
// here you need to return instead of **super.requestChildFocus(child, focused);**
    }

and xml looks like this

  <com.views.widget.MyScrollView
        android:focusable="false"
        android:focusableInTouchMode="false"
    android:id="@+id/root_scroll_view"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="wrap_content">

</com.views.widget.MyScrollView >



回答2:


Based on Er Pragati Singh's answer I did not override requestChildFocus(View child, View focused) but computeScrollDeltaToGetChildRectOnScreen(Rect rect).

Overriding requestChildFocus will also prevent activating the on screen keyboard when touching an EditText which already has focus, while computeScrollDeltaToGetChildRectOnScreen is only used to calculate the delta scroll inside requestChildFocus to bring the View in sight. So overriding this function keeps all other routines intact.

Java:

public class MyScrollView extends ScrollView {
    public MyScrollView(Context context) {
        super(context);

    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    @Override
    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
        // This function calculates the scroll delta to bring the focused view on screen.
        // -> To prevent unsolicited scrolling to the focued view we'll just return 0 here.
        //
        return 0;
    }
}

XML:

<YOUR.PAKAGE.NAME.MyScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
</YOUR.PAKAGE.NAME.MyScrollView>


来源:https://stackoverflow.com/questions/36332922/android-tabhost-auto-scroll-vertically-in-side-scrollview-on-tabchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!