ScrollView 滚动条知识点

来源:互联网 发布:淘宝最好的店铺 编辑:程序博客网 时间:2024/06/02 06:16

ScrollView   滚动条

特点:

    1. 可以给包裹在ScrollVIew标签内的控件添加上下滚动效果
    2. ScrollView中直接的子控件最多只能有1个

使用方式:

 

  • 当只需要给一个控件添加滚动功能时:

 

在该控件外嵌套一个ScrollView控件即可。
如:
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <TextView android:text="Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="100sp"
            android:textColor="#ff0000"

            />

</ScrollView>

 

 

  • 如想要个n个控件一起添加滚动功能:

    1. 先将者n个控件同时添加到一个布局标签中
    2. 再将该布局标签作为ScrollVIew的子控件

如:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        
>
        <TextView android:text="Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="100sp"
            android:textColor="#ff0000"
            
/>
        <TextView android:text="Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="100sp"
            android:textColor="#00ff00"
            
/>
    </LinearLayout>

</ScrollView>

 

 

当ScrollView与ListView进行嵌套时,会发生冲突,冲突的表现为:

如果ListView的高度设置的是match_parent,那么显示到屏幕上时,ListView的高度只会显示一条item的高度

 

解决方式:

    1. 创建一个ListView的子类作为自定义控件
    2. 在该子类中重写onMeasure方法

 

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int height = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, height);
}

 

 

3. 用该子类替换ListView进行使用即可

 

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        
>
        <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:id="@+id/pager"
            
/>

        <myapp.com.week7_day04.MyListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lv"
            
></myapp.com.week7_day04.MyListView>
    </LinearLayout>
</ScrollView>

 

 

当ViewPager与ListView同时被显示在ScrollView中,在初始显时ViewPager会被显示在屏幕外,需要下拉才能看到ViewPager,此bug的解决方式为:

 

在代码中获取ListView对象后,通过ListView对象调用setFocusable(false)方法即可

0 0
原创粉丝点击