Android之自制的分页表格控件 .

           网页上经常有分页表格的出现,同样的在Android上也可以实现。Android本身并没有直接提供表格这个控件,一般可以用GridView来实现比较简单,但是每个数据显示的长宽会一样。当然,也可以用ListView来实现,这个灵活定义每个数据显示的长宽。还有一种,是采用布局TableLayout来实现等等。这里用GridView,来实现一个。下载路径: http://download.csdn.net/source/3275713

            它有几个特点:

             1、实现分页;

             2、简便的翻页按钮设置;

             3、点击顶部字段名称会改变排序方式;

             4、使用方便,只需几个参数。

           (一)截图

                  

 

                   

                

                  

           (二)关键部分:

             1、视图架构:

             该分页视图控件,由三部分组成:顶部:字段视图:gv_titles,主体:数据视图:gv_body,底部:分页按钮视图:bottomlayout。      

            2、SQl分页查询语句:

           

  1. //查询语句   
  2. sql += " Limit " + TableRowCount + " Offset " + stratIndex;  

           3、排序方式的改变

          

  1. String sql = "select * from (" +   SimpleTable.this.sql +   
  2.             " Limit " + TableRowCount + " Offset " + pageID * TableRowCount + ") tempTable order by " +  
  3.             items[arg2][0] ;  
  4.             if(isDesc[arg2]) {  
  5.                 sql += " asc ";  
  6.                 isDesc[arg2] = false;  
  7.             }else {  
  8.                 sql += " desc ";  
  9.                 isDesc[arg2] = true;  
  10.             }  
  11.             Log.e("sql", sql);    
  12.             toPage(0, sql);  
  13.         }  
  14.     });  

              

           (三)代码:

             1、数据项布局文件:items.xml

            

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout android:id="@+id/LinearLayout01"  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent" android:background="#555555"  
  5.     android:layout_height="wrap_content">  
  6.     <TextView android:layout_below="@+id/ItemImage" android:text="TextView01"  
  7.         android:id="@+id/ItemText" android:bufferType="normal"  
  8.         android:singleLine="true" android:background="#000000"  
  9.         android:layout_width="fill_parent" android:gravity="center"  
  10.         android:layout_margin="1dip" android:layout_gravity="center"  
  11.         android:layout_height="wrap_content">  
  12.     </TextView>  
  13. </LinearLayout>  

             2、Activity类:PaginatingTable

             

  1. package com.myandroid.test;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.view.ViewGroup;  
  9. import android.view.ViewGroup.LayoutParams;  
  10. import android.widget.LinearLayout;  
  11.   
  12. public class PaginatingTable extends Activity {  
  13.     private LinearLayout linearLayout;  
  14.     private SimpleTable simpleTable;  
  15.     private String[][] items;  
  16.     private String sql;  
  17.       
  18.       
  19.     /** Called when the activity is first created. */  
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.           
  25.         linearLayout = (LinearLayout)findViewById(R.id.linearLayout);  
  26.           
  27.         //要查询的字段和对应显示的名称   
  28.         items = new String[][]{  
  29.             {"id""序列"},  
  30.             {"name""姓名"},  
  31.             {"time""登陆时间"},  
  32.         };  
  33.           
  34.         //插入一些数据测试用   
  35.         SQLiteUtility.insertSomething(this);  
  36.         //查询语句   
  37.         String sql = "select * from myTable";  
  38.         //创建分页表格视图,只需要传入几个参数   
  39.         SimpleTable simpleTable = new SimpleTable(this, items, sql, 7);  
  40.          
  41.          
  42.         linearLayout.addView(simpleTable);  
  43. //       addContentView(simpleTable,  new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,    
  44. //              ViewGroup.LayoutParams.WRAP_CONTENT));   
  45.           
  46.           
  47.      
  48.     }  
  49. }  

             3、分页表格类:SimpleTable

               

  1. package com.myandroid.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8.   
  9. import android.content.Context;  
  10. import android.database.Cursor;  
  11. import android.graphics.Color;  
  12. import android.graphics.Shader.TileMode;  
  13. import android.graphics.Typeface;  
  14. import android.util.Log;  
  15. import android.view.Gravity;  
  16. import android.view.View;  
  17. import android.view.ViewGroup.LayoutParams;  
  18. import android.widget.AdapterView;  
  19. import android.widget.AdapterView.OnItemClickListener;  
  20. import android.widget.AdapterView.OnItemSelectedListener;  
  21. import android.widget.ArrayAdapter;  
  22. import android.widget.Button;  
  23. import android.widget.GridView;  
  24. import android.widget.LinearLayout;  
  25. import android.widget.SimpleAdapter;  
  26. import android.widget.Spinner;  
  27. import android.widget.TextView;  
  28. import android.widget.Toast;  
  29. import android.view.View.OnClickListener;  
  30.   
  31.   
  32. public class SimpleTable extends LinearLayout implements OnClickListener, OnItemSelectedListener,  
  33.                                                         OnItemClickListener{  
  34.     private Context context;    //上下文   
  35.     private GridView gv_titles; //字段视图   
  36.     private GridView gv_body;   //数据视图   
  37.     private LinearLayout bottomLayout;  //视图底部布局   
  38.     private Button bt_next, bt_pre, bt_first, bt_last;  //按钮:下一页、上一页、首页、尾页   
  39.     private TextView tv_page, tv_count;   
  40.     private Spinner sp_page;    //页码下拉框   
  41.     private String[][] items;   //[字段][显示的名称]   
  42.     private String sql;         //查询语句   
  43.     private SimpleAdapter titlesAdatper;    //字段视图适配器   
  44.     private SimpleAdapter datasAdatper; //数据视图适配去   
  45.     private int TableRowCount;          //每页显示条数   
  46.     private int pageID;                 //当前页码   
  47.     private int TotalCount;             //总记录条数   
  48.     private int pageCount;              //总页数   
  49.     private String TableName;           //表名和查询条件   
  50.     private String[] fields;            //字段名称   
  51.     private boolean[] isDesc;           //排序方式标记:false-递增排序,true-递减排序   
  52.     private ArrayList<HashMap<String, String>>  dataList;   //数据集合   
  53.       
  54.     public SimpleTable(Context context) {  
  55.         super(context);  
  56.         this.context = context;  
  57.     }  
  58.       
  59.     /** 
  60.      * 表格视图 
  61.      * @param context       上下文  
  62.      * @param items         字段名和对应显示名称 
  63.      * @param sql           SQl查询语句 
  64.      * @param displayNum    每页的最大记录数 
  65.      */  
  66.     public SimpleTable(Context context, String[][] items, String sql, int TableRowCount) {  
  67.         super(context);  
  68.         this.context = context;  
  69.         this.items = items;  
  70.         this.sql = sql.replace(";""");  
  71.         this.TableRowCount = TableRowCount;  
  72.           
  73.         //排序方式标记:false-递增排序,true-递减排序   
  74.         isDesc = new boolean[items.length];  
  75.         //当前页码   
  76.         pageID = 0;  
  77.         //表名称和查询条件   
  78.         TableName = sql.toLowerCase().substring(sql.toLowerCase().indexOf(" from ")+5, sql.length()).trim();  
  79.         //记录总数   
  80.         TotalCount = SQLiteUtility.getCount(context, "select count(*) from " + TableName);  
  81.         //总页码   
  82.         pageCount = TotalCount%TableRowCount==0? TotalCount/TableRowCount-1 : TotalCount/TableRowCount;  
  83.         //字段名称   
  84.         fields = new String[items.length];  
  85.         for (int i = 0; i < items.length; i++) {  
  86.             fields[i] = items[i][0];  
  87.         }  
  88.           
  89.         setField(); //字段视图   
  90.         setBody();  //数据视图   
  91.         setBottomLayout();  //底部视图   
  92.         setOrientation(LinearLayout.VERTICAL);    
  93.         addView(gv_titles); //添加视图   
  94.         addView(gv_body);  
  95.         addView(bottomLayout);  
  96.           
  97.     }  
  98.       
  99.       
  100.       
  101.     /** 
  102.      * 设置字段视图 
  103.      */  
  104.     private void setField() {  
  105.         gv_titles = new GridView(context);  
  106.         gv_titles.setNumColumns(items.length);  
  107.           
  108.         //字段标题   
  109.         ArrayList<HashMap<String, String>> titles = new ArrayList<HashMap<String, String>>();  
  110.         for(int i = 0; i < items.length; i++) {  
  111.             HashMap<String, String> map = new HashMap<String, String>();  
  112.             map.put("title", items[i][1]);  
  113.             titles.add(map);  
  114.         }  
  115.         titlesAdatper = new SimpleAdapter(context, titles,   
  116.                 R.layout.items, new String[]{"title"}, new int[] {R.id.ItemText});  
  117.         gv_titles.setAdapter(titlesAdatper);  
  118.           
  119.         //点击字段标题,改变排序方式   
  120.         gv_titles.setOnItemClickListener(new OnItemClickListener() {  
  121.   
  122.             @Override  
  123.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
  124.                     long arg3) {  
  125.   
  126.                 String sql = "select * from (" +   SimpleTable.this.sql +   
  127.                 " Limit " + TableRowCount + " Offset " + pageID * TableRowCount + ") tempTable order by " +  
  128.                 items[arg2][0] ;  
  129.                 if(isDesc[arg2]) {  
  130.                     sql += " asc ";  
  131.                     isDesc[arg2] = false;  
  132.                 }else {  
  133.                     sql += " desc ";  
  134.                     isDesc[arg2] = true;  
  135.                 }  
  136.                 Log.e("sql", sql);    
  137.                 toPage(0, sql);  
  138.             }  
  139.         });  
  140.     }  
  141.       
  142.     /** 
  143.      * 设置表格数据视图 
  144.      */  
  145.     private void setBody() {  
  146.         gv_body = new GridView(context);  
  147.         gv_body.setNumColumns(items.length);  
  148.               
  149.         toPage(0this.sql);    //转到第一页   
  150.         gv_body.setOnItemClickListener(this);   //点击数据事件   
  151.     }  
  152.       
  153.     /** 
  154.      * 设置底部翻页视图, 
  155.      * 由如下组成:首页、上一页、下一页、尾页、页码选择、当期页码提示 
  156.      */  
  157.     private void setBottomLayout() {  
  158.         //底部容器   
  159.         bottomLayout = new LinearLayout(context);  
  160.         bottomLayout.setOrientation(LinearLayout.HORIZONTAL);  
  161.         bottomLayout.setLayoutParams(new LayoutParams(  
  162.                 LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
  163.         //翻页按钮   
  164.         bt_pre = new Button(context);   //上一页   
  165.         bt_next = new Button(context);  //下一页   
  166.         bt_first = new Button(context); //首页   
  167.         bt_last = new Button(context);  //尾页   
  168.         sp_page = new Spinner(context); //页码   
  169.         tv_page = new TextView(context);//页码   
  170.           
  171.         //设置文本   
  172.         bt_pre.setText("上一页");  
  173.         bt_next.setText("下一页");  
  174.         bt_first.setText("首页");  
  175.         bt_last.setText("尾页");  
  176.         tv_page.setText("页码:");  
  177.           
  178.         //设置页码下拉框选项   
  179.         List<Integer> list = new ArrayList<Integer>();  
  180.         for(int i = 0; i <= pageCount; i++) {  
  181.             list.add(i);  
  182.         }  
  183.         ArrayAdapter<Integer> pageAdapter = new ArrayAdapter<Integer>(context, android.R.layout.simple_spinner_item, list);  
  184.         sp_page.setAdapter(pageAdapter);  
  185.           
  186.         //设置事件   
  187.         sp_page.setOnItemSelectedListener(this);    //设置下拉框事件   
  188.         bt_first.setOnClickListener(this);  
  189.         bt_pre.setOnClickListener(this);  
  190.         bt_last.setOnClickListener(this);  
  191.         bt_next.setOnClickListener(this);  
  192.           
  193.         //设置文本大小   
  194.         bt_first.setTextSize(12);  
  195.         bt_pre.setTextSize(12);  
  196.         bt_last.setTextSize(12);  
  197.         bt_next.setTextSize(12);  
  198.         tv_page.setTextSize(12);  
  199.           
  200.         //添加到底部容器   
  201.         bottomLayout.addView(bt_first);  
  202.         bottomLayout.addView(bt_pre);  
  203.         bottomLayout.addView(bt_next);  
  204.         bottomLayout.addView(bt_last);  
  205.         bottomLayout.addView(tv_page);  
  206.         bottomLayout.addView(sp_page);    
  207.     }  
  208.   
  209.     //设置显示大小   
  210.     public void setSize(View v) {  
  211.         v.setLayoutParams(new android.view.ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  212.     }  
  213.       
  214.     /** 
  215.      * 翻页点击事件 
  216.      */  
  217.     @Override  
  218.     public void onClick(View v) {  
  219.   
  220.         if(v == bt_first) { //第一页   
  221.             pageID = 0;  
  222.                   
  223.         }else if(v == bt_last) {    //最后一页   
  224.             if(pageCount == 0) {  
  225.                 return;  
  226.             }  
  227.             pageID = pageCount;  
  228.                   
  229.         }else if(v == bt_next) {    //下一页   
  230.             if(pageID < pageCount) {  
  231.                 ++pageID;  
  232.             } else {  
  233.                 return;  
  234.             }  
  235.               
  236.         }else if(v == bt_pre) { //上一页   
  237.             if(pageID <= 0){  
  238.                 return;  
  239.             }else {  
  240.                 --pageID;  
  241.             }  
  242.         }  
  243.         sp_page.setSelection(pageID);  
  244.     }  
  245.       
  246.   
  247.     /** 
  248.      * 页码下拉框选择事件 
  249.      */  
  250.     @Override  
  251.     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,  
  252.             long arg3) {  
  253.           
  254.         pageID = arg2;  
  255.         Log.e("onItemSelected:""selected");  
  256.         toPage(pageID * TableRowCount, this.sql);  
  257.     }  
  258.   
  259.     @Override  
  260.     public void onNothingSelected(AdapterView<?> arg0) {  
  261.         // TODO Auto-generated method stub   
  262.           
  263.     }  
  264.       
  265.     /** 
  266.      * 跳转页面 
  267.      * @param stratIndex 开始页码 
  268.      * @param sql 查询语句 
  269.      */  
  270.     public void toPage(int stratIndex, String sql) {  
  271.         //查询语句   
  272.         sql += " Limit " + TableRowCount + " Offset " + stratIndex;  
  273.         //获取查询结果集合   
  274.         dataList = SQLiteUtility.query2(context, sql, fields);  
  275.         //设置适配器   
  276.         SimpleAdapter simpleAdapter = new SimpleAdapter(context, dataList,   
  277.                 R.layout.items, new String[]{"item"}, new int[] {R.id.ItemText});  
  278.         gv_body.setAdapter(simpleAdapter);  //重新添加适配器   
  279.     }  
  280.   
  281.     /** 
  282.      * 数据项点击事件 
  283.      */  
  284.     @Override  
  285.     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {  
  286.           
  287.         Toast.makeText(context, ((HashMap<String, String>)dataList.get(arg2)).get("item"),   
  288.                 Toast.LENGTH_SHORT).show();  
  289.     }  
  290.   
  291. }  
  

             4、SQLite操作类:SQLiteUtility

               

  1. package com.myandroid.test;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.ArrayList;  
  5. import java.util.Date;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import android.app.ActivityGroup;  
  11. import android.app.AlertDialog;  
  12. import android.content.Context;  
  13. import android.database.Cursor;  
  14. import android.database.sqlite.SQLiteDatabase;  
  15. import android.util.Log;  
  16. import android.widget.Toast;  
  17.   
  18. import android.database.Cursor;  
  19. import android.database.SQLException;  
  20. import android.database.sqlite.SQLiteDatabase;  
  21.   
  22. public class SQLiteUtility{  
  23.       
  24.     private static final int MODE_PRIVATE = 0x0;  
  25.     private static final String DATABASE = "myDB2";  
  26.     private static SQLiteDatabase db;  
  27.       
  28.       
  29.     /** 
  30.      * 插入一些数据 
  31.      */  
  32.     public static void insertSomething(Context context) {  
  33.           
  34.         Cursor cursor;  
  35.         int count = 0;  
  36.         String sql = "CREATE TABLE myTable  (id int not null, " +  
  37.         "name text not null," +  
  38.         "time text not null );";  
  39.         SimpleDateFormat bartDateFormat =  
  40.             new SimpleDateFormat("yyyy-MM-dd-HH:mm");  
  41.         Date date = new Date();  
  42.         try {   
  43.              db = context.openOrCreateDatabase(DATABASE, MODE_PRIVATE, null);  
  44.              String sqlCheckExsit = "select count(*) as c from Sqlite_master  where type ='table' and name ='myTable' ";     
  45.              cursor = db.rawQuery(sqlCheckExsit, null);     
  46.              if(cursor.moveToNext()){     
  47.                      count = cursor.getInt(0);     
  48.                      if(count <= 0){     
  49.                              db.execSQL(sql);       
  50.                      }else {  
  51.                          db.execSQL("drop table myTable");  
  52.                          db.execSQL(sql);  
  53.                      }  
  54.              }  
  55.                
  56.              for(int i = 0; i <30; i++) {  
  57.                 String insertSql = "insert into myTable ("  
  58.                         + "id, name, time) values('" + i + "', 'admin','"  
  59.                         + bartDateFormat.format(date) + "');";  
  60.                 db.execSQL(insertSql);  
  61.              }  
  62.             Log.e("insertSql""ok");  
  63.         }finally {  
  64.             db.close();  
  65.         }  
  66.   
  67.     }  
  68.       
  69.       
  70.     /** 
  71.      * 查询 
  72.      * @param context 上下文 
  73.      * @param sql     SQl查询语句 
  74.      * @param fields  字段名集合 
  75.      * @return  查询结果集 List<String>类型 
  76.      */  
  77.     public static List<String> query(Context context, String sql, String[] fields) {  
  78.         List<String> dataList = new ArrayList<String>();  
  79.         Cursor cursor;  
  80.   
  81.         try {  
  82.             db = context.openOrCreateDatabase(DATABASE, MODE_PRIVATE, null);  
  83.   
  84.             cursor = db.rawQuery(sql, null);  
  85.             if (cursor != null) {  
  86.                 while (cursor.moveToNext()) {  
  87.                     for (int i = 0; i < fields.length; i++) {  
  88.                         String temp = cursor.getString(cursor  
  89.                                 .getColumnIndex(fields[i]));  
  90.                         dataList.add(temp);  
  91.                     }  
  92.                 }  
  93.             }  
  94.         }catch(Exception e) {  
  95.             new AlertDialog.Builder(context)      
  96.             .setIcon(android.R.drawable.ic_dialog_alert)          
  97.             .setTitle("数据库连接错误:")                 
  98.             .setMessage("数据访问异常。")                        
  99.             .show();                                              
  100.         } finally {  
  101.             db.close();  
  102.         }  
  103.         return dataList;  
  104.     }  
  105.       
  106.     /** 
  107.      * 数据记录总条数 
  108.      * @param context 上下文 
  109.      * @param sql     SQL查询语句 
  110.      * @return        记录条数 
  111.      */  
  112.     public static int getCount(Context context, String sql) {  
  113.           
  114.         int totalCounty = 0;  
  115.         try {  
  116.             db = context.openOrCreateDatabase(DATABASE, MODE_PRIVATE, null);  
  117.             Cursor cursor = db.rawQuery(sql, null);  
  118.             cursor.moveToFirst();  
  119.             totalCounty = cursor.getInt(0);  
  120.         } catch (Exception e) {  
  121.             new AlertDialog.Builder(context)  
  122.                     .setIcon(android.R.drawable.ic_dialog_alert)  
  123.                     .setTitle("数据库连接错误:").setMessage("数据访问异常。").show();  
  124.         } finally {  
  125.             db.close();  
  126.         }  
  127.         return totalCounty;  
  128.     }  
  129.   
  130.   
  131.     /** 
  132.      * 查询 
  133.      * @param context 上下文 
  134.      * @param sql     SQl查询语句 
  135.      * @param fields  字段名集合 
  136.      * @return  查询结果集 ArrayList<HashMap<String,String>>类型 
  137.      */  
  138.     public static  ArrayList<HashMap<String,String>>  query2(Context context, String sql, String[] fields) {  
  139.           
  140.         ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();  
  141.         Cursor cursor;  //游标   
  142.         try{      
  143.             db = context.openOrCreateDatabase(DATABASE, MODE_PRIVATE, null);    //连接数据库   
  144.               
  145.             cursor = db.rawQuery(sql, null);    //获取数据集游标   
  146.   
  147.             if (cursor != null) {  
  148.                 while (cursor.moveToNext()) {   //游标递增,访问数据集   
  149.   
  150.                     for (int i = 0; i < fields.length; i++) {  
  151.                         String temp = cursor.getString(cursor   //获取对应数据项   
  152.                                 .getColumnIndex(fields[i]));      
  153.                         HashMap<String, String> map = new HashMap<String, String>();  
  154.                         map.put("item", temp);  
  155.                         dataList.add(map);  
  156.   
  157.                     }  
  158.                 }  
  159.             }  
  160.         }catch(Exception e) {  
  161.             new AlertDialog.Builder(context)      
  162.             .setIcon(android.R.drawable.ic_dialog_alert)          
  163.             .setTitle("数据库连接错误:")                 
  164.             .setMessage("数据访问异常。")                        
  165.             .show();                                              
  166.         }finally {  
  167.             cursor = null;  
  168.             db.close();  
  169.         }  
  170.         return dataList;  
  171.     }  
  172.       
  173.       
  174.       
  175.   
  176.       
  177. }  
 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值