Android listview 表格显示和自动循环显示

本文介绍如何在Android中使用TableLayout和ListView结合实现动态表格显示,并解决宽度和分隔线问题。通过styles.xml、activity_main.xml、item_regular.xml、RegularAdapter.java以及MainActivity.java的配置,实现表格的自动调整宽度、对齐列和分隔线。同时,通过Handler和setSelection方法实现ListView的自动循环滚动效果。

在Android中,有时候也需要使用如HTML的表格一样显示数据。
Android没有直接提供表格控件,但可通过其他方式实现,一样可以达到预期的效果。
数据量固定、单元格等宽的可以使用GridView来实现。而数据集不确定,单元格宽度可拉伸收缩时可使用TableLayout和ListView相结合的方式实现。
网络上有很多文章,虽然都实现了,但或多或少还有点不完美,具体体现在宽度及表格分隔线的问题上。

1.表格宽度问题

TableLayout 有两个属性 shrinkColumns(自动收缩)以及stretchColumns(自动扩充),例如
android:shrinkColumns=”1,3,7” android:stretchColumns=”1,3,7” 分别表示在第1,3,7列上自动收缩/扩充,列编号从0开始,也就是会根据屏幕的宽度自动调整内容的显示,屏幕宽度不够时内容会换行显示,否则屏幕宽度不够,后面的列的就看不到了。当设置为“*”时表示应用到所有列。
仅仅设置这个还是不行,原因是单元格的内容有长短,表格标题的内容有长短,如果单元格都设置为自动调整宽度的话,那么会出现各个列不能对齐的现象,即分割线错开来了,这并不是我们所期望的。为了对齐列,所以需要指定固定宽度大小,而不能设置自动宽度或wrap_content或match_parent。
由于手机的屏幕分辨率多种多样,所以固定宽度的设置需要在代码中计算,而不能写死在xml文件中。

2.表格线(分隔线)问题

单元格之间的分隔线其实很好实现,只要用一个宽度为1dp的带颜色的线就可以了。
<View android:layout_width="1dp" android:layout_height="match_parent" android:background="#F00"/>

先看下效果图:

表格图片

3.styles.xml

为了复用代码,将一些属性提取出来,放到styles.xml中,styles.xml文件在values目录下面。

 <!-- 分隔符 -->
    <style name="list_item_seperator_layout">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">1dp</item>
        <item name="android:background">@android:color/holo_green_light</item>
    </style>

    <style name="list_item_cell_seperator_layout">
        <item name="android:layout_width">1dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:background">@android:color/holo_green_light</item>
    </style>
    <!-- 字体 -->
    <style name="textViewHead">
        <item name="android:textSize">30sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">#F00</item>
        <item name="android:gravity">center</item>
    </style>
    <style name="textViewCell">
        <item name="android:textSize">27sp</item>
        <item name="android:textColor">#F00</item>
        <item name="android:gravity">center</item>
    </style>
4.activity_main.xml 表格布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">

    <View style="@style/list_item_seperator_layout" />

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:shrinkColumns="7"
        android:stretchColumns="7">
        <TableRow
            android:id="@+id/stock_list_header_row"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <View style="@style/list_item_cell_seperator_layout" />
            <TextView
                android:id="@+id/head1"
                style="@style/textViewHead"
                android:text="发车时间" />
            <View style="@style/list_item_cell_seperator_layout" />
            <TextView
                android:id="@+id/head2"
                style="@style/textViewHead"
                android:text="车牌号" />
            <View style="@style/list_item_cell_seperator_layout" />
            <TextView
                android:id="@+id/head3"
                style="@style/textViewHead"
                android:text="里程" />
            <View style="@style/list_item_cell_seperator_layout" />
            <TextView
                android:id="@+id/head4"
                style="@style/textViewHead"
                android:text="终点站" />
            <View style="@style/list_item_cell_seperator_layout" />
        </TableRow>
    </TableLayout>
    <View style="@style/list_item_seperator_layout"
        android:layout_height="2dp"
        />
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/holo_green_light"
        android:dividerHeight="1dp" />
</LinearLayout>

表格头的每列宽度在代码中指定,最后一列采用自适应(自动收缩或扩充)。
表格头的列宽需要和单元格的列宽一致。

5. item_regular.xml 列表行的布局

这里直接使用水平方向的LinearLayout表示列表行,每列直接放一个View作为分隔线即可。列的宽度需要在代码中重新设置(在Adapter中)。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal"
    tools:context=".adapter.RegularAdapter">
    <View style="@style/list_item_cell_seperator_layout" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/regularFcsj"
        style="@style/textViewCell"
        android:text="text1" />
    <View style="@style/list_item_cell_seperator_layout" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/regularCph"
        style="@style/textViewCell"
        android:text="text12" />
    <View style="@style/list_item_cell_seperator_layout" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/regularLc"
        style="@style/textViewCell"
        android:text="text13" />
    <View style="@style/list_item_cell_seperator_layout" />
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/regularZDZ"
        style="@style/textViewCell"
        android:text="text14" />
    <View style="@style/list_item_cell_seperator_layout" />
</LinearLayout>

其实表格头部也可以直接用一个LinearLayout实现即可,不需要TableLayout。表格头的列宽需要和单元格的列宽一致。

6.RegularAdapter.java 列表适配器
package com.jykj.departure.adapter;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.jykj.departure.R;
import com.jykj.departure.entity.Regular;

import java.util.List;


public class RegularAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private List<Regular> mRegulars;
    private DisplayMetrics dm ;

    public RegularAdapter(Context context, List<Regular> regulars) {
        mInflater = (LayoutInflater)context.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        dm = context.getResources().getDisplayMetrics();
        mRegulars = regulars;
    }

    @Override
    public int getCount() {
        if(mRegulars == null) return 0;
        return mRegulars.size();
    }

    @Override
    public Object getItem(int position) {
        return mRegulars.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v;
        if (convertView == null) {
            v = mInflater.inflate(R.layout.item_regular, parent,
                    false);
        } else {
            v = convertView;
        }
        //Log.v("Regular", position + " " + v.hashCode() + "  " + checkedPosition);
        Regular item = (Regular) getItem(position);
        TextView tv1=(TextView) v.findViewById(R.id.regularCph);
        TextView tv2 = (TextView) v.findViewById(R.id.regularFcsj);
        TextView tv3  = (TextView) v.findViewById(R.id.regularLc);
        TextView tv4 = (TextView) v.findViewById(R.id.regularZDZ);

        tv1.setWidth(dm.widthPixels/4);
        tv2.setWidth(dm.widthPixels/4);
        tv3.setWidth(dm.widthPixels/4);
        tv4.setWidth(dm.widthPixels/4);

        tv1.setText(item.get_cph());
        tv2.setText(item.get_fcsj());
        tv3.setText(""+item.get_lc() + "");
        tv4.setText(""+item.get_mdzmc() + "");

        return v;
    }
}

上面的关键代码是设置4个TextView的宽度。

7.自动循环显示

利用Handler的post方法以及ListView的setSelection方法实现循环显示功能。
注意销毁时要移除handler上的Runnable

@Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
    boolean isEnd = false;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //计算偏移量
            int pos =isEnd?0: listView.getLastVisiblePosition();
            listView.setSelection(pos);
            Log.e("TAG","current selected:"+pos);
            isEnd = pos>=regulars.size()-1;
            handler.postDelayed(this, 3000);
        }
    };
8. MainActivity.java
package com.jykj.departure;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.AutoScrollHelper;
import android.support.v4.widget.ListViewAutoScrollHelper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.jykj.departure.adapter.RegularAdapter;
import com.jykj.departure.entity.Regular;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {
    private ListView listView;
    private List<Regular> regulars;
    private final static int TIMESPAN = 3*1000;//3秒
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DisplayMetrics dm = getResources().getDisplayMetrics();

        ((TextView)findViewById(R.id.head1)).setWidth(dm.widthPixels/4);
        ((TextView)findViewById(R.id.head2)).setWidth(dm.widthPixels/4);
        ((TextView)findViewById(R.id.head3)).setWidth(dm.widthPixels/4);
        ((TextView)findViewById(R.id.head4)).setWidth(dm.widthPixels/4);

        regulars = new ArrayList<>();
        for(int i=0;i<30;i++) {
            Regular r = new Regular();
            r.set_cph(i%3==0?"琼B"+i: "琼Abcd"+i);
            r.set_fcsj("15:30");
            r.set_lc(35+i);
            r.set_mdzmc(i%4==0?"儋州"+i:"三亚海口文昌"+i);
            regulars.add(r);
        }
        ListAdapter adapter = new RegularAdapter(this,regulars);
        setListAdapter(adapter);
        Log.e("TAG",dm.widthPixels+","+dm.heightPixels+","+dm.widthPixels/4);
        listView = (ListView) findViewById(android.R.id.list);
         /*AutoScrollHelper ash = new ListViewAutoScrollHelper(listView);
        listView.setOnTouchListener(ash);
        ash.setEnabled(true);*/
        handler.postDelayed(runnable,TIMESPAN);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
    boolean isEnd = false;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //计算偏移量
            int pos =isEnd?0: listView.getLastVisiblePosition();
            listView.setSelection(pos);
            Log.e("TAG","current selected:"+pos);
            isEnd = pos>=regulars.size()-1;
            handler.postDelayed(this, TIMESPAN);
        }
    };
}

上面的关键代码是设置表头的4个TextView的宽度。

336.《道德经》第七十九章3 打开你的心,发出你的善
原文:故天之道,损有余而益不足。人之道则不然,损不足而奉有余。
翻译:天之道,是损减有余来补充不足。人类社会世俗的作法却不然,而是损减贫穷不足来供奉富贵有余。
人类渴望公平是在基因中遗传的。激发人类内心中“善”的部分,是社会稳定的关键。

339.《道德经》第八十章2 道理你都懂,就是没做到
原文:柔之胜刚也,弱之胜强也,天下莫弗知也,而莫之能行也。
翻译:柔能胜刚,弱能胜强,天下没有不知道的,却没有能够做到的。
人要克服动物性,走向更高的层次。

<think> 我们正在寻找在Android Studio中显示表格的方法。根据引用内容,我们可以找到一些线索: 引用[3]提到了TableLayout表格布局),这是Android中的一种布局方式,专门用于表格形式的显示。 引用[4]中提到了使用TextViewEditText来构建布局,虽然没有直接说表格,但说明我们可以通过组合视图来构建表格。 因此,在Android Studio中显示表格,主要有两种方法: 1. 使用TableLayout:这是Android SDK中提供的专门用于表格布局。 2. 使用RecyclerView或ListView:通过自定义布局,实现类似于表格的网格效果(特别是当需要滚动显示大量数据时)。 根据引用[2],滚动条功能在展示长条商品或广告时常用,所以如果表格数据量很大,我们可以考虑使用RecyclerView来实现滚动表格。 下面我们分别介绍这两种方法: ### 方法1:使用TableLayout TableLayout是ViewGroup的子类,它将子视图(TableRow)排列成行列。每一行是一个TableRow,每个TableRow中的视图组成单元格。 **步骤:** 1. 在XML布局文件中添加TableLayout。 2. 在TableLayout中添加TableRow(每一行)。 3. 在TableRow中添加视图(如TextView、EditText等)作为单元格。 示例代码(activity_main.xml): ```xml <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="*"> <!-- 所有列可拉伸 --> <!-- 表头 --> <TableRow android:background="#CCCCCC"> <TextView android:text="姓名" android:padding="10dp"/> <TextView android:text="年龄" android:padding="10dp"/> <TextView android:text="性别" android:padding="10dp"/> </TableRow> <!-- 数据行 --> <TableRow> <TextView android:text="张三" android:padding="10dp"/> <TextView android:text="25" android:padding="10dp"/> <TextView android:text="男" android:padding="10dp"/> </TableRow> </TableLayout> ``` ### 方法2:使用RecyclerView 当表格数据量较大且需要滚动时,我们可以使用RecyclerView。通过设置GridLayoutManager,可以实现网格布局(类似于表格)。 **步骤:** 1. 在build.gradle中添加RecyclerView依赖(如果尚未添加): ```gradle implementation 'androidx.recyclerview:recyclerview:1.2.1' ``` 2. 创建每行(item)的布局(例如,一个包含多个TextView的水平LinearLayout,每个TextView代表一列)。 3. 创建适配器(Adapter)来绑定数据。 4. 在Activity中设置RecyclerView,使用GridLayoutManager,并设置列数(相当于表格的列数)。 示例代码(item_table_row.xml): ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="10dp"/> <TextView android:id="@+id/age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="10dp"/> <TextView android:id="@+id/gender" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="10dp"/> </LinearLayout> ``` 适配器示例(TableAdapter.java): ```java public class TableAdapter extends RecyclerView.Adapter<TableAdapter.ViewHolder> { private List<Person> mData; public static class ViewHolder extends RecyclerView.ViewHolder { TextView name, age, gender; public ViewHolder(View itemView) { super(itemView); name = itemView.findViewById(R.id.name); age = itemView.findViewById(R.id.age); gender = itemView.findViewById(R.id.gender); } } public TableAdapter(List<Person> data) { this.mData = data; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_table_row, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Person person = mData.get(position); holder.name.setText(person.getName()); holder.age.setText(String.valueOf(person.getAge())); holder.gender.setText(person.getGender()); } @Override public int getItemCount() { return mData.size(); } } ``` 在Activity中设置RecyclerView(MainActivity.java): ```java RecyclerView recyclerView = findViewById(R.id.recyclerView); // 设置布局管理器,1列(这里每行是一个item,所以列数1,但item内部有多个列,因此实际上是横向排列) recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 或者使用GridLayoutManager,但此处我们希望每行显示一个item(该item内部已经包含多列),所以用LinearLayoutManager即可。 // 如果每行要显示多个item(每个item是一个单元格),则使用GridLayoutManager并设置列数为表格的列数。 // 创建数据 List<Person> data = new ArrayList<>(); data.add(new Person("张三", 25, "男")); data.add(new Person("李四", 30, "女")); TableAdapter adapter = new TableAdapter(data); recyclerView.setAdapter(adapter); ``` 注意:如果每个单元格独立为一个item,则使用GridLayoutManager,并设置列数为表格的列数,同时每个item的布局就是一个单元格(如一个TextView)。但通常表格的一行是一个item,里面包含多个单元格(如多个TextView),所以使用LinearLayoutManager(垂直方向)即可。 ### 总结 - 对于简单的静态表格,使用TableLayout。 - 对于动态数据且需要滚动的表格,使用RecyclerView(每个item代表一行,内部再分成多个列)更为高效。 §§相关问题§§ 1. TableLayoutRecyclerView在显示表格时各有什么优缺点? 2. 如何在RecyclerView中实现表头固定? 3. 如何为TableLayout添加边框线? </think> 在 Android Studio 中显示表格数据主要有以下三种实现方法,根据引用内容结合最佳实践整理如下: ### 一、TableLayout 表格布局(基础表格实现) ```xml <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="*"> <!-- 列等宽 --> <!-- 表头 --> <TableRow android:background="#EEEEEE"> <TextView android:text="姓名" android:padding="10dp"/> <TextView android:text="年龄" android:padding="10dp"/> <TextView android:text="部门" android:padding="10dp"/> </TableRow> <!-- 数据行 --> <TableRow> <TextView android:text="张三" android:padding="10dp"/> <TextView android:text="28" android:padding="10dp"/> <TextView android:text="技术部" android:padding="10dp"/> </TableRow> </TableLayout> ``` **特点**: - 内置表格布局控件,无需额外依赖 - 通过 `<TableRow>` 定义行,内部视图自动成为列 - 适合静态数据展示[^3] ### 二、RecyclerView + GridLayout(动态表格) 更适合动态数据复杂交互: 1. 添加依赖: ```gradle implementation 'androidx.recyclerview:recyclerview:1.3.2' ``` 2. XML布局: ```xml <androidx.recyclerview.widget.RecyclerView android:id="@+id/rvTable" android:layout_width="match_parent" android:layout_height="match_parent" app:layoutManager="androidx.recyclerview.widget.GridLayoutManager" app:spanCount="3"/> <!-- 定义列数 --> ``` 3. Java代码适配器: ```java // 自定义适配器 public class TableAdapter extends RecyclerView.Adapter<TableAdapter.ViewHolder> { private List<TableItem> data; class ViewHolder extends RecyclerView.ViewHolder { TextView tvContent; public ViewHolder(View itemView) { super(itemView); tvContent = itemView.findViewById(R.id.tvCell); } } @Override public void onBindViewHolder(ViewHolder holder, int position) { TableItem item = data.get(position); holder.tvContent.setText(item.getContent()); } } // 设置数据 GridLayoutManager layoutManager = new GridLayoutManager(this, 3); // 3列 recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(new TableAdapter(dataList)); ``` ### 三、第三方表格库(高级功能) 推荐库: 1. **SmartTable**(开源表格库) ```gradle implementation 'com.github.huangyanbin:SmartTable:2.2.0' ``` ```java TableData<User> tableData = new TableData<>("员工表", userList, new Column<>("姓名", "name"), new Column<>("年龄", "age"), new Column<>("部门", "department") ); SmartTable<User> table = findViewById(R.id.table); table.setTableData(tableData); ``` ### 选择建议 | 方法 | 适用场景 | 特点 | |------|----------|------| | `TableLayout` | 简单静态表格 | 原生支持,开发快 | | `RecyclerView` | 动态数据/大数据量 | 支持滚动,性能优[^2] | | 第三方库 | 复杂表格需求 | 支持排序/过滤/样式定制 | > **最佳实践**:对于需要 *数据循环显示* 的场景(如数据库查询结果),推荐使用 RecyclerView + GridLayoutManager 方案,既保证性能又支持动态更新[^4]。静态配置数据可选择 TableLayout 快速实现。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值