天天看点

Android 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"/>

先看下效果图:

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

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">dp</item>
        <item name="android:background">@android:color/holo_green_light</item>
    </style>

    <style name="list_item_cell_seperator_layout">
        <item name="android:layout_width">dp</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">sp</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">sp</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 ;
        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/);
        tv2.setWidth(dm.widthPixels/);
        tv3.setWidth(dm.widthPixels/);
        tv4.setWidth(dm.widthPixels/);

        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?: listView.getLastVisiblePosition();
            listView.setSelection(pos);
            Log.e("TAG","current selected:"+pos);
            isEnd = pos>=regulars.size()-;
            handler.postDelayed(this, );
        }
    };
           

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秒
    @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/);
        ((TextView)findViewById(R.id.head2)).setWidth(dm.widthPixels/);
        ((TextView)findViewById(R.id.head3)).setWidth(dm.widthPixels/);
        ((TextView)findViewById(R.id.head4)).setWidth(dm.widthPixels/);

        regulars = new ArrayList<>();
        for(int i=;i<30;i++) {
            Regular r = new Regular();
            r.set_cph(i%==?"琼B"+i: "琼Abcd"+i);
            r.set_fcsj("15:30");
            r.set_lc(+i);
            r.set_mdzmc(i%==?"儋州"+i:"三亚海口文昌"+i);
            regulars.add(r);
        }
        ListAdapter adapter = new RegularAdapter(this,regulars);
        setListAdapter(adapter);
        Log.e("TAG",dm.widthPixels+","+dm.heightPixels+","+dm.widthPixels/);
        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?: listView.getLastVisiblePosition();
            listView.setSelection(pos);
            Log.e("TAG","current selected:"+pos);
            isEnd = pos>=regulars.size()-;
            handler.postDelayed(this, TIMESPAN);
        }
    };
}

           

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

336.《道德经》第七十九章3 打开你的心,发出你的善

原文:故天之道,损有余而益不足。人之道则不然,损不足而奉有余。

翻译:天之道,是损减有余来补充不足。人类社会世俗的作法却不然,而是损减贫穷不足来供奉富贵有余。

人类渴望公平是在基因中遗传的。激发人类内心中“善”的部分,是社会稳定的关键。

339.《道德经》第八十章2 道理你都懂,就是没做到

原文:柔之胜刚也,弱之胜强也,天下莫弗知也,而莫之能行也。

翻译:柔能胜刚,弱能胜强,天下没有不知道的,却没有能够做到的。

人要克服动物性,走向更高的层次。