Android中使用HorizontalScrollView和TableLayout遇到的问题

    技术2022-05-19  29

     今天在做一个控件,想实现的效果是,在一行内显示N个图片(或其他),要求每个图片的间隔是一样的。

    之前用LinearLayout来做,里面包含多个ImageView,可是没有达到想要的效果,这个后面再研究下。

    今天突然想到用TableLayout来做,之前没有用过这种布局。

    最终效果如下:

     

    现将制作过程中遇到的问题列出。

    1.  各view不是均匀占着整行。xml如下:

    <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableRow> <TextView android:text="文字" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> </TableRow> </TableLayout>

    效果为:

     

    很明显这不是我要的效果。

    在TableLayout加入属性android:stretchColumns="*"即可。

     

    2. 实现左右拖动

        这个控件包含的view有多少个,我无法知道,所以当一行显示不完所有的view时,我需要左右拖动。

       于是我用HorizontalScrollView来包含该TableLayout,可是当view个数很少,一行可以放下时,显示的效果如上图一样。

        查了API,发现设置HorizontalScrollView的参数android:fillViewport="true" 即可。

        最终效果对应的xml为:

      <?xml version="1.0" encoding="utf-8"?> <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" > <!-- android:shrinkColumns="*" --> <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*"> <TableRow> <TextView android:text="文字" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> <ImageView android:src="@drawable/icon" android:gravity="center" /> </TableRow> </TableLayout> </HorizontalScrollView>

     


    最新回复(0)