Android使用TableLayou动态布局实例

openkk 12年前

实现主要功能:

 * 1.使用TableLayout动态布局展示,可动态添加和删除.
 * 2.初始化时显示动态展示,初始化的数据改造后可来自数据库. 
 * 3.重置时到初始化状态.
 * 4.保存时去重检查,参见代码中去重算法.

 

首先,建立实体类:

package tgb.lk.tablelayout;        public class Dict {            private int id;        private String name;        private int orders;        private String desc;        private int types;                //get,set方法.             @Override        public String toString() {            return "Dict [id=" + id + ", name=" + name + ", orders=" + orders                    + ", types=" + types + "]";        }        } 

其次,建立数据层方法接口:

    package tgb.lk.tablelayout;                import java.util.ArrayList;        import java.util.List;                import android.content.Context;                public class DictDaoImpl {                    public DictDaoImpl(Context context) {                    }                    public boolean isExist() {                return false;            }                    public List<Dict> getDictItem(String dictId) {                String[] dicts = new String[] { "华东", "华南", "华北", "华中", "西南", "东北" };                List<Dict> retList = new ArrayList<Dict>();                for (int j = 0; j < dicts.length; j++) {                    Dict dict = new Dict();                    dict.setName(dicts[j]);                    dict.setId(j);                    dict.setOrders(j);                    dict.setTypes(1000);                    retList.add(dict);                }                return retList;            }                    public long insert(Dict entity) {                return 1L;            }                    public void delete(int id) {            }                    public void update(Dict entity) {            }                    public Dict get(Object id) {                Dict dict = new Dict();                dict.setId(1);                dict.setName("华东");                dict.setOrders(1);                dict.setTypes(1000);                return dict;            }                    public void delete(Integer... ids) {            }        }  
然后,建立layout布局dict_item.xml:
    <?xml version="1.0" encoding="utf-8"?>        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:scrollbars="none" >                    <LinearLayout                android:id="@+id/dictLayout"                android:layout_width="fill_parent"                android:layout_height="fill_parent"                android:orientation="vertical"                android:scrollbars="" >                        <TextView                    android:id="@+id/title"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:text="业务字典管理" />                        <LinearLayout                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:orientation="horizontal" >                            <TextView                        android:layout_width="80dp"                        android:layout_height="wrap_content"                        android:text="名称:" />                            <EditText                        android:id="@+id/name"                        android:layout_width="200dp"                        android:layout_height="wrap_content"                        android:hint="请输入业务字典名称"                        android:maxLength="20"                        android:singleLine="true" />                </LinearLayout>                        <TableLayout                    android:id="@+id/dictTable"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:stretchColumns="1" >                            <TableRow >                                <TextView                            android:layout_width="60dp"                            android:layout_gravity="left"                            android:padding="3dip"                            android:text="序号"                            android:textStyle="bold" />                                <TextView                            android:layout_gravity="center"                            android:padding="3dip"                            android:text="字典名称"                            android:textStyle="bold" />                                <TextView                            android:layout_gravity="right"                            android:padding="3dip"                            android:text=" 操作 "                            android:textStyle="bold" />                    </TableRow>                </TableLayout>                        <LinearLayout                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:gravity="right"                    android:orientation="horizontal" >                            <Button                        android:id="@+id/btnCancel"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:layout_margin="8dp"                        android:text=" 关 闭 " />                            <Button                        android:id="@+id/btnReset"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:layout_margin="8dp"                        android:text=" 重 置 " />                            <Button                        android:id="@+id/btnAdd"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:layout_margin="8dp"                        android:text=" 添 加 " />                            <Button                        android:id="@+id/btnOK"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:layout_margin="8dp"                        android:text=" 保 存 " />                </LinearLayout>            </LinearLayout>                </ScrollView>

最后,建立逻辑主类:

    package tgb.lk.tablelayout;                import java.util.ArrayList;        import java.util.HashMap;        import java.util.List;        import java.util.Map;                import android.app.Activity;        import android.content.Intent;        import android.os.Bundle;        import android.text.TextUtils;        import android.view.Gravity;        import android.view.View;        import android.view.View.OnClickListener;        import android.widget.Button;        import android.widget.EditText;        import android.widget.TableLayout;        import android.widget.TableRow;        import android.widget.TextView;        import android.widget.Toast;                /**        * 实现功能:         * 1.使用TableLayout动态布局展示,可动态添加和删除.        * 2.初始化时显示动态展示,初始化的数据改造后可来自数据库.         * 3.重置时到初始化状态.        * 4.保存时去重检查,参见代码中去重算法.        *         * @author likun date: 2012-04-07        */        public class MainActivity extends Activity {            private Button btnAdd = null;            private Button btnOK = null;            private Button btnReset = null;            private Button btnCancel = null;                    private EditText nameET = null;                    private int entity_id = 0;            private String entity_name = "";                    private DictDaoImpl dao = null;            private TableLayout table = null;            private int orders = 0; // 用户记录最大的orders值                     @Override            protected void onCreate(Bundle savedInstanceState) {                super.onCreate(savedInstanceState);                setContentView(R.layout.dict_item);                        // 实例化按钮并设置监听器.                 btnAdd = (Button) findViewById(R.id.btnAdd);                btnOK = (Button) findViewById(R.id.btnOK);                btnReset = (Button) findViewById(R.id.btnReset);                btnCancel = (Button) findViewById(R.id.btnCancel);                        btnAdd.setOnClickListener(listener);                btnOK.setOnClickListener(listener);                btnReset.setOnClickListener(listener);                btnCancel.setOnClickListener(listener);                        // 实例化EditText                 nameET = (EditText) findViewById(R.id.name);                        // Intent intent = getIntent();                         entity_id = 1; // intent.getIntExtra(CrmConstances.ID, 0);                 entity_name = "区域";// intent.getStringExtra(CrmConstances.NAME);                         nameET.setText(entity_name);                        table = (TableLayout) findViewById(R.id.dictTable);                        initDictItemTable();            }                    OnClickListener listener = new OnClickListener() {                        @Override                public void onClick(View v) {                            switch (v.getId()) {                    case R.id.btnAdd:                        appendNewRow(table);                        break;                    case R.id.btnOK:                        // 组名称不能为空.                         if (TextUtils.isEmpty(nameET.getText().toString().trim())) {                            toastShow("名称不能为空,操作失败!");                            nameET.requestFocus(); // 设定焦点                             break;                        }                        if (dao == null) {                            dao = new DictDaoImpl(MainActivity.this);                        }                                String entityNameET = nameET.getText().toString().trim();                                if (entity_id != 0) {                            Dict entity = dao.get(entity_id);                            // 组名发生改变时,判断组名称是否重复                             if (!entity.getName().equals(entityNameET)) {                                if (dao.isExist()) {                                    toastShow("名称[" + entityNameET + "]重复,操作失败!");                                    nameET.selectAll();                                    nameET.requestFocus();                                    break;                                }                                entity.setName(entityNameET);                                dao.update(entity);                            }                                    Map<String, Dict> dictMap = new HashMap<String, Dict>();                            List<Dict> dictAddList = new ArrayList<Dict>();                            List<Dict> dictUpdateList = new ArrayList<Dict>();                            List<Dict> dictDeleteList = new ArrayList<Dict>();                            Map<String, String> map = new HashMap<String, String>();                            // 从界面得到业务字典对象                             for (int i = 1; i < table.getChildCount(); i++) {                                // 得到TableRow对象                                 TableRow row = (TableRow) table.getChildAt(i);                                String dictId = ((TextView) row.getChildAt(0))                                        .getText().toString();                                String dictOrders = ((EditText) row.getChildAt(1))                                        .getText().toString();                                String dictName = ((EditText) row.getChildAt(2))                                        .getText().toString();                                        // 构建Dict对象                                 Dict dict = new Dict();                                if (!TextUtils.isEmpty(dictName)) {                                    dict.setName(dictName);                                    // 检查名称是否重复.                                     if (map.containsKey(dictName)) {                                        toastShow("名称重复,请检查,保存失败!");                                        return;                                    }                                    map.put(dictName, dictName);                                    if (!TextUtils.isEmpty(dictOrders)) {                                        dict.setOrders(Integer.parseInt(dictOrders));                                    } else {                                        dict.setOrders(orders);                                    }                                    if (!TextUtils.isEmpty(dictId)) {                                        dict.setId(Integer.parseInt(dictId));                                        dictMap.put(dictId, dict);                                    } else {                                        dict.setId(0);                                        dict.setTypes(1);                                        dictAddList.add(dict);                                    }                                } else {                                    toastShow("名称不能为空,保存失败!");                                    return;                                }                                    }                            if (dao == null) {                                dao = new DictDaoImpl(MainActivity.this);                            }                            // 在数据库中取出Dict对象                             List<Dict> list = new ArrayList<Dict>();                            if (entity_id != 0) {                                list = dao.getDictItem(String.valueOf(entity_id));                            }                            // 比较数据库中取出的对象和界面上构造的对象,找出那些需要修改那些需要删除那些需要添加                             for (Dict dict : list) {                                String dict_id = String.valueOf(dict.getId());                                if (dictMap.containsKey(dict_id)) {                                    Dict temp = dictMap.get(dict_id);                                    if (!dict.getName().equals(temp.getName())                                            || dict.getOrders() != temp.getOrders()) {                                        dict.setName(temp.getName());                                        dict.setOrders(temp.getOrders());                                        dictUpdateList.add(dict);                                    }                                } else {                                    dictDeleteList.add(dict);                                }                            }                                    // 添加对象并建立关系                             for (Dict dict : dictAddList) {                                // 插入对象                                 Long itemId = dao.insert(dict);                                // 建立关系...                                 // ....                             }                                    // 修改业务字典对象                             for (Dict dict : dictUpdateList) {                                dao.update(dict);                            }                                    // 删除不存在的业务字典                             Integer[] ids = new Integer[dictDeleteList.size()];                            for (int j = 0; j < dictDeleteList.size(); j++) {                                Dict dict2 = dictDeleteList.get(j);                                ids[j] = dict2.getId();                            }                            dao.delete(ids);                            toastShow("修改[" + entityNameET + "]成功!");                        }                                // setResult(1);                         // MainActivity.this.finish();                         break;                    case R.id.btnReset:                        // 若为添加则重置为空,若为修改则重置为打开前的数据.                         nameET.setText(entity_name);                        initDictItemTable();                        toastShow("重置成功,请重新输入");                        // setResult(CrmConstances.RESULT_FAILURE);                         break;                    case R.id.btnCancel:                        // setResult(CrmConstances.RESULT_FAILURE);                         MainActivity.this.finish(); // 结束自己,即回到打开之前的Activity.                         toastShow("关闭");                        break;                    default:                        break;                    }                        }            };                    public void toastShow(String text) {                Toast.makeText(this, text, 1000).show();            }                    private void appendNewRow(final TableLayout table) {                TableRow row = new TableRow(this);                row.setId(0);                orders++;                        TextView dictItemId = new TextView(this);                dictItemId.setText("");                dictItemId.setVisibility(View.GONE);                        EditText order = new EditText(this);                order.setText(String.valueOf(orders));                order.setPadding(3, 3, 3, 3);                order.setWidth(40);                order.setGravity(Gravity.CENTER);                        EditText dictName = new EditText(this);                dictName.setText("");                dictName.setHint("请输入业务字典名称");                dictName.setPadding(3, 3, 3, 3);                dictName.setWidth(190);                dictName.setGravity(Gravity.CENTER);                        Button oper = new Button(this);                oper.setText(" 删除 ");                oper.setPadding(3, 3, 3, 3);                order.setWidth(60);                oper.setGravity(Gravity.CENTER);                oper.setOnClickListener(new OnClickListener() {                    @Override                    public void onClick(View v) {                        table.removeView(table.findViewById(0));                    }                });                        row.addView(dictItemId);                row.addView(order);                row.addView(dictName);                row.addView(oper);                        table.addView(row);                        // LinearLayout linear = (LinearLayout) findViewById(R.id.dictLayout);                 // ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) linear                 // .getLayoutParams();                 // params.height = LayoutParams.WRAP_CONTENT;                 // params.width = LayoutParams.FILL_PARENT;                 // linear.setLayoutParams(params);             }                    public void initDictItemTable() {                if (dao == null) {                    dao = new DictDaoImpl(this);                }                List<Dict> list = new ArrayList<Dict>();                if (entity_id != 0) {                    list = dao.getDictItem(String.valueOf(entity_id));                }                table.removeAllViews();                TableRow row1 = new TableRow(this);                TextView dictItemId1 = new TextView(this);                dictItemId1.setText("");                dictItemId1.setVisibility(View.GONE);                        TextView order1 = new TextView(this);                order1.setText(" 序号 ");                order1.setPadding(3, 3, 3, 3);                order1.setWidth(40);                order1.setGravity(Gravity.CENTER);                        TextView dictName1 = new TextView(this);                dictName1.setText("字典名称");                dictName1.setPadding(3, 3, 3, 3);                dictName1.setWidth(190);                dictName1.setGravity(Gravity.CENTER);                        TextView oper1 = new TextView(this);                oper1.setText(" 操作 ");                oper1.setPadding(3, 3, 3, 3);                oper1.setWidth(60);                oper1.setGravity(Gravity.CENTER);                        row1.addView(dictItemId1);                row1.addView(order1);                row1.addView(dictName1);                row1.addView(oper1);                table.addView(row1);                orders = 0;                for (Dict dict : list) {                    orders = Math.max(dict.getOrders(), orders);// 取较大的作为新orders.                     TableRow row = new TableRow(this);                    row.setId(dict.getId());                    TextView dictItemId = new TextView(this);                    dictItemId.setText(String.valueOf(dict.getId()));                    dictItemId.setVisibility(View.GONE);                            EditText order = new EditText(this);                    order.setText(String.valueOf(dict.getOrders()));                    order.setPadding(3, 3, 3, 3);                    order.setWidth(40);                    order.setGravity(Gravity.CENTER);                            EditText dictName = new EditText(this);                    dictName.setText(dict.getName());                    dictName.setPadding(3, 3, 3, 3);                    dictName.setWidth(190);                    dictName.setGravity(Gravity.CENTER);                            Button oper = new Button(this);                    oper.setId(dict.getId() + 1000); // 设置这个Id,用于计算得到TableRow的Id.                     oper.setText(" 删除 ");                    oper.setPadding(3, 3, 3, 3);                    oper.setWidth(60);                    oper.setGravity(Gravity.CENTER);                    oper.setOnClickListener(new OnClickListener() {                        @Override                        public void onClick(View v) {                            System.out.println(v.getId());                            table.removeView(table.findViewById(v.getId() - 1000));                        }                    });                            row.addView(dictItemId);                    row.addView(order);                    row.addView(dictName);                    row.addView(oper);                            table.addView(row, new TableLayout.LayoutParams());                }                // LinearLayout linear = (LinearLayout) findViewById(R.id.dictLayout);                 // ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) linear                 // .getLayoutParams();                 // params.height = LayoutParams.WRAP_CONTENT;                 // params.width = LayoutParams.FILL_PARENT;                 // linear.setLayoutParams(params);             }                }
Android使用TableLayou动态布局实例