[Android] Android最简单ScrollView和ListView滚动冲突解决方案

[Question]问题描述:

单独的ListView列表能自动垂直滚动,但当将ListView嵌套在ScrollView后,会和ScrollView的滚动滑块冲突,造成ListView滑块显示不完整。

 

activity_main.xml表现:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
****此处省略ScrollView的修饰代码***
>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="test"/>

<ListView
android:id="@+id/list_class"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"/>
</LinearLayout>

</ScrollView>

 

 

[Solution]解决方法:

第一步:自定义ListViewForScrollView类:  ListViewForScrollView.java

 

package com.jack.helloen.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * 自定义一个类继承自ListView,通过重写其onMeasure方法,达到对ScrollView适配的效果。
 */
public class ListViewForScrollView extends ListView {
    public ListViewForScrollView(Context context) {
        super(context);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs,
                                 int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    /**
     * 重写该方法,达到使ListView适应ScrollView的效果
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

 

第二步: MainActivity.java里增加兼容patch

 

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

       //ListView兼容ScrollView
        sv = (ScrollView) findViewById(R.id.main_scroll);
        sv.smoothScrollTo(0, 0);
}

 

第三步:布局文件xml 里 引用自定义 组件

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/main_scroll"
*** >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <TextView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:text="test"/>


        <com.jack.helloen.ui.ListViewForScrollView
            android:id="@+id/list_class"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none"/>
    </LinearLayout>
</ScrollView>

 

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/10657559.html

转载请著名出处!谢谢~~

 

posted @ 2019-04-04 23:25  wukong1688  阅读(2472)  评论(0编辑  收藏  举报