利用TableLayout实现的类XLS表

转载请注明出处王亟亟向大牛之路努力!!
最近有一个私活是要做一个像XLS的表,然后里面可能还有一些算法和逻辑,网上找了点资料看了一些别人的代码,呈现给大家看,希望项目中用到的话可以派上用场。
先上图:
初始化的状态
利用TableLayout实现的类XLS表

输入内容计算结果
利用TableLayout实现的类XLS表

添加行
利用TableLayout实现的类XLS表

初始化
利用TableLayout实现的类XLS表

表单属性:
Dict.java

public class Dict {

    private int id;
    private String name;
    private int number;
    private float price;
    private float totle;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public float getTotle() {
        return totle;
    }
    public void setTotle(float totle) {
        this.totle = totle;
    }
}

填充数据DictDaoImpl

public class DictDaoImpl {

    public DictDaoImpl(Context context) {

    }

    public boolean isExist() {
        return false;
    }

    public List<Dict> getDictItem(String dictId) {
        String[] dicts = new String[5];
        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+1);
//          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) {
    }
}

主要实现的Activity
MainActivity

@SuppressLint("ResourceAsColor")
public class MainActivity extends Activity {

    private ImageView add, clear, save, back;
    private DisplayMetrics displayMetrics;
    private int entity_id = 0;
    private DictDaoImpl dao = null;
    private TableLayout table = null;
    private int id = 0; // 用户记录最大的orders值
    private TextView finalnumber, finaltotle;
    private int numberber = 0;
    private float totlele = 0;
    private Handler mhandler = null;
    private List<Dict> templist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dict_item);
        displayMetrics = new DisplayMetrics();
        (MainActivity.this).getWindowManager().getDefaultDisplay()
                .getMetrics(displayMetrics);
        // 实例化按钮并设置监听器.
        add = (ImageView) findViewById(R.id.add);
        clear = (ImageView) findViewById(R.id.clear);
        save = (ImageView) findViewById(R.id.save);
        back = (ImageView) findViewById(R.id.back);
        add.setOnClickListener(listener);
        clear.setOnClickListener(listener);
        save.setOnClickListener(listener);
        back.setOnClickListener(listener);
        entity_id = 1; // intent.getIntExtra(CrmConstances.ID, 0);

        table = (TableLayout) findViewById(R.id.dictTable);
        initDictItemTable();
        getfoottable();

    }

    OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
            case R.id.add:
                appendNewRow(table);
                break;
            case R.id.clear:
                initDictItemTable();
                getfoottable();
                Toast.makeText(MainActivity.this, "重置成功", Toast.LENGTH_SHORT).show();
//              toast("重置成功");
                break;
            case R.id.save:

                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
            }

        }
    };

    private void appendNewRow(final TableLayout table) {
        TableRow row = new TableRow(this);
        row.setId(0);
        id++;
        final Dict dict = new Dict();
        final EditText projectadd = new EditText(this);
        final EditText numberadd = new EditText(this);
        final EditText priceadd = new EditText(this);
        final EditText totleadd = new EditText(this);

        projectadd.setWidth(displayMetrics.widthPixels / 4);
//      projectadd.setLayoutParams(new LayoutParams(displayMetrics.widthPixels / 4, LayoutParams.WRAP_CONTENT));
        projectadd.setGravity(Gravity.LEFT);
        projectadd.setSingleLine(true);
        projectadd.setBackgroundResource(R.drawable.bg_city_search_normal);

        totleadd.setWidth(displayMetrics.widthPixels / 4);
//      totleadd.setLayoutParams(new LayoutParams(displayMetrics.widthPixels / 4, LayoutParams.WRAP_CONTENT));
        totleadd.setGravity(Gravity.LEFT);
        totleadd.setBackgroundResource(R.drawable.bg_city_search_normal);
        totleadd.setSingleLine(true);
        totleadd.setInputType(InputType.TYPE_NULL);

        priceadd.setWidth(displayMetrics.widthPixels / 4);
        priceadd.setGravity(Gravity.LEFT);
        priceadd.setBackgroundResource(R.drawable.bg_city_search_normal);
        priceadd.setSingleLine(true);
        priceadd.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL
                | InputType.TYPE_CLASS_NUMBER);
        priceadd.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                if (!"".equals(priceadd.getText() + "")
                        && !"".equals(numberadd.getText() + "")) {
                    totleadd.setText(Float.parseFloat(arg0 + "")
                            * Integer.parseInt(numberadd.getText() + "") + "");
                    dict.setTotle(Float.parseFloat(totleadd.getText() + ""));
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mhandler.sendMessage(msg);
                } else {
                    totleadd.setText("");
                    dict.setTotle(0);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mhandler.sendMessage(msg);
                }

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });

        numberadd.setWidth(displayMetrics.widthPixels / 4);
//      numberadd.setLayoutParams(new LayoutParams(displayMetrics.widthPixels / 4, LayoutParams.WRAP_CONTENT));
        numberadd.setGravity(Gravity.LEFT);
        numberadd.setBackgroundResource(R.drawable.bg_city_search_normal);
        numberadd.setSingleLine(true);
        numberadd.setInputType(InputType.TYPE_CLASS_NUMBER);
        numberadd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(9)});
        numberadd.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                if (!"".equals(priceadd.getText() + "")
                        && !"".equals(numberadd.getText() + "")) {
                    totleadd.setText(Float.parseFloat(priceadd.getText() + "")
                            * Integer.parseInt(arg0 + "") + "");
                    dict.setTotle(Float.parseFloat(priceadd.getText() + "")
                            * Integer.parseInt(arg0 + ""));
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mhandler.sendMessage(msg);
                } else {
                    totleadd.setText("");
                    dict.setTotle(0);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mhandler.sendMessage(msg);
                }

                if (!"".equals(numberadd.getText() + "")) {
                    dict.setNumber(Integer.parseInt(arg0 + ""));
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mhandler.sendMessage(msg);

                } else {
                    dict.setNumber(0);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = list;
                    mhandler.sendMessage(msg);
                }


            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });
        list.add(dict);
        row.addView(projectadd);
        row.addView(priceadd);
        row.addView(numberadd);
        row.addView(totleadd);
        table.addView(row, id);
    }

    List<Dict> list;

    @SuppressLint("ResourceAsColor")
    public void initDictItemTable() {
        if (dao == null) {
            dao = new DictDaoImpl(this);
        }

        list = new ArrayList<Dict>();
        if (entity_id != 0) {
            list = dao.getDictItem(String.valueOf(entity_id));
        }
        table.removeAllViews();

        TableRow row1 = new TableRow(this);

        TextView project1 = new TextView(this);
        project1.setText("项目");
        project1.setWidth(displayMetrics.widthPixels / 4);
        project1.setGravity(Gravity.CENTER);
        project1.setTextSize(18);
        project1.setTextColor(R.color.white);
        project1.setBackgroundColor(R.color.black);

        TextView price1 = new TextView(this);
        price1.setText("单价");
        price1.setWidth(displayMetrics.widthPixels / 4);
        price1.setGravity(Gravity.CENTER);
        price1.setTextSize(18);
        price1.setTextColor(R.color.white);
        price1.setBackgroundColor(R.color.black);

        TextView number1 = new TextView(this);
        number1.setText("数量");
        number1.setWidth(displayMetrics.widthPixels / 4);
        number1.setGravity(Gravity.CENTER);
        number1.setTextSize(18);
        number1.setTextColor(R.color.white);
        number1.setBackgroundColor(R.color.black);

        final TextView totle1 = new TextView(this);
        totle1.setText("金额");
        totle1.setWidth(displayMetrics.widthPixels / 4);
        totle1.setGravity(Gravity.CENTER);
        totle1.setTextSize(18);
        totle1.setTextColor(R.color.white);
        totle1.setBackgroundColor(R.color.black);

        // row1.addView(dictItemId1);
        row1.addView(project1);
        row1.addView(price1);
        row1.addView(number1);
        row1.addView(totle1);
        table.addView(row1);
        id = 0;
        for (final Dict dict : list) {
            id = Math.max(dict.getId(), id);// 取较大的作为新orders.
            TableRow row = new TableRow(this);
            row.setId(dict.getId());
            EditText project = new EditText(this);
            final EditText price = new EditText(this);
            final EditText number = new EditText(this);
            final EditText totle = new EditText(this);

            project.setWidth(displayMetrics.widthPixels / 4);
            project.setGravity(Gravity.LEFT);
            project.setSingleLine(true);
            project.setBackgroundResource(R.drawable.bg_city_search_normal);

            price.setWidth(displayMetrics.widthPixels / 4);
            price.setGravity(Gravity.LEFT);
            price.setBackgroundResource(R.drawable.bg_city_search_normal);
            price.setSingleLine(true);
            price.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL
                    | InputType.TYPE_CLASS_NUMBER);
            price.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {
                    if (!"".equals(price.getText() + "")
                            && !"".equals(number.getText() + "")) {
                        totle.setText(Float.parseFloat(arg0 + "")
                                * Integer.parseInt(number.getText() + "") + "");
                        dict.setTotle(Float.parseFloat(arg0 + "")
                                * Integer.parseInt(number.getText() + ""));
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = list;
                        mhandler.sendMessage(msg);
                    } else {
                        totle.setText("");
                        dict.setTotle(0);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = list;
                        mhandler.sendMessage(msg);
                    }


                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                }

            });

            number.setWidth(displayMetrics.widthPixels / 4);
            number.setGravity(Gravity.LEFT);
            number.setBackgroundResource(R.drawable.bg_city_search_normal);
            number.setSingleLine(true);
            number.setInputType(InputType.TYPE_CLASS_NUMBER);
            number.setFilters(new InputFilter[]{new InputFilter.LengthFilter(9)});
            number.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence arg0, int start,
                        int before, int count) {

                    if (!"".equals(price.getText() + "")
                            && !"".equals(number.getText() + "")) {
                        totle.setText(Float.parseFloat(price.getText() + "")
                                * Integer.parseInt(arg0 + "") + "");
                        dict.setTotle(Float.parseFloat(totle.getText() + ""));
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = list;
                        mhandler.sendMessage(msg);

                    } else {
                        totle.setText("");
                        dict.setTotle(0);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = list;
                        mhandler.sendMessage(msg);
                    }
                    Log.w("111", start + "----" + before + "----" + count);
                    if (!"".equals(number.getText() + "")) {
                        dict.setNumber(Integer.parseInt(arg0 + ""));
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = list;
                        mhandler.sendMessage(msg);
                    } else {
                        dict.setNumber(0);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = list;
                        mhandler.sendMessage(msg);
                    }



                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {

                }

                @Override
                public void afterTextChanged(Editable arg0) {

                }
            });

            totle.setWidth(displayMetrics.widthPixels / 4);
            totle.setGravity(Gravity.LEFT);
            totle.setBackgroundResource(R.drawable.bg_city_search_normal);
            totle.setSingleLine(true);
            totle.setInputType(InputType.TYPE_NULL);

            row.addView(project);
            row.addView(price);
            row.addView(number);
            row.addView(totle);
            table.addView(row, new TableLayout.LayoutParams());
        }

    }

    private void getfoottable() {

        TableRow footrow = new TableRow(this);
        TextView finalname = new TextView(this);
        finaltotle = new TextView(this);
        finalnumber = new TextView(this);

        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    numberber = 0;
                    totlele =0;
                    templist = (List<Dict>) msg.obj;
                    for (int i = 0; i < templist.size(); i++) {
                        numberber = numberber + templist.get(i).getNumber();
                        totlele = totlele +templist.get(i).getTotle();
                    }
                    finalnumber.setText(numberber + "");
                    finaltotle.setText(totlele+"");
                }
            }
        };

        finalname.setText("合计");
        finalname.setWidth(displayMetrics.widthPixels / 4);
        finalname.setGravity(Gravity.CENTER);
        finalname.setTextSize(18);
        finalname.setTextColor(R.color.white);
        finalname.setBackgroundColor(R.color.black);

        TextView finalname1 = new TextView(this);
        finalname1.setWidth(displayMetrics.widthPixels / 4);
        finalname1.setTextSize(18);
        finalname1.setTextColor(R.color.white);
        finalname1.setBackgroundColor(R.color.black);

        finalnumber.setWidth(displayMetrics.widthPixels / 4);
        finalnumber.setGravity(Gravity.LEFT);
        finalnumber.setBackgroundResource(R.drawable.bg_city_search_normal);
        finalnumber.setSingleLine(true);
        finalnumber.setTextSize(18);

        finaltotle.setWidth(displayMetrics.widthPixels / 4);
        finaltotle.setGravity(Gravity.LEFT);
        finaltotle.setTextSize(18);
        finaltotle.setBackgroundResource(R.drawable.bg_city_search_normal);
        finaltotle.setSingleLine(true);

        footrow.addView(finalname);
        footrow.addView(finalname1);
        footrow.addView(finalnumber);
        footrow.addView(finaltotle);

        table.addView(footrow, id + 1, new TableLayout.LayoutParams());
    }


}

布局文件dict_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="@color/black"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/app_back_click"
            android:layout_width="112dp"
            android:layout_height="match_parent"
            android:background="#0000"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:paddingLeft="6dp"
            android:visibility="visible" >

            <ImageView
                android:id="@+id/back"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:layout_marginLeft="4dp"
                android:src="@drawable/icon_back" />

            <TextView
                android:id="@+id/app_title_tv_left"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="4dp"
                android:gravity="center"
                android:singleLine="true"
                android:text="返回"
                android:textColor="#ffffff"
                android:textSize="16sp"
                android:visibility="gone" />
        </LinearLayout>

        <TextView
            android:id="@+id/app_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="marquee"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:gravity="center"
            android:marqueeRepeatLimit="marquee_forever"
            android:singleLine="true"
            android:text="例子哈哈"
            android:textColor="#ffffff"
            android:textSize="20sp" />

        <LinearLayout
            android:id="@+id/app_add_click"
            android:layout_width="132dp"
            android:layout_height="match_parent"
            android:background="#0000"
            android:gravity="center_vertical|right"
            android:orientation="horizontal"
            android:paddingRight="6dp"
            android:visibility="visible" >

            <ImageView
                android:id="@+id/add"
                android:layout_width="28dp"
                android:layout_height="28dp"
                android:layout_marginRight="15dp"
                android:src="@drawable/app_title_add" />

            <ImageView
                android:id="@+id/clear"
                android:layout_width="28dp"
                android:layout_height="28dp"
                android:layout_marginRight="15dp"
                android:src="@drawable/white_rubbish_normal" />

            <ImageView
                android:id="@+id/save"
                android:layout_width="28dp"
                android:layout_height="28dp"
                android:layout_marginRight="4dp"
                android:src="@drawable/icon_save" />
        </LinearLayout>
    </LinearLayout>

    <ScrollView
        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="" >

            <TableLayout
                android:id="@+id/dictTable"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="8dp" >

                <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>
    </ScrollView>

</LinearLayout>

具体的实例 可以看例子 源码链接
访问密码 46aa
有问题欢迎+Q 452270579联系交流,谢谢

上一篇:工具类更新第二弹,继续加速中!


下一篇:自用工具类整理,加速开发GOGOGO