android开发实战-记账本APP(二)

继昨天的开发,继续完成今天的内容。

(一)开始构建一些业务逻辑,开始构建记账本的添加一笔记账的功能。

①对fab按钮的click时间进行修改,创建一个AlertDialog.Builder对象,因此我们给dialog添加一个布局,命名为new_cost_data.xml,位于他的布局很简单,我们只需要设置两个编辑框,和一个时间选择框即可。

new_cost_data.xml

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

    <EditText
        android:id="@+id/et_cost_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:hint="Cost Title"/>

    <EditText
        android:id="@+id/et_cost_money"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:hint="Cost Money"/>
    <DatePicker
        android:id="@+id/dp_cost_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:datePickerMode="spinner"
        android:calendarViewShown="false"/>
</LinearLayout>

 

 

 ②然后回到主程序,在fab点击事件里创建一个 LayoutInflater用他来创建view,将新布局传到新建立的View对象,这样就可以获取到布局文件的内容,获取后将该布局设置给dialog对象,然后需要给dialog设置监听事件,当点击ok的监听事件,就将从布局中获取的信息传给一个CostBean对象,在用数据库进行添加,收集数据的mCostBeanList对象也要进行添加,最后再进行刷新(mAdapter.notifyDataSetChanged();),点击cancel就会取消该view界面,最后不要忘了显示该dialog。

MainActivity代码:

 

package com.example.xlfbook;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<CostBean> mCostBeanList;
    private DatabaseHelper mdatabaseHelper;
    private CostListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mdatabaseHelper=new DatabaseHelper(this);
        mCostBeanList=new ArrayList<>();
        ListView costList=(ListView)findViewById(R.id.lv_main);
        initCostData();
        mAdapter = new CostListAdapter(this, mCostBeanList);
        costList.setAdapter(mAdapter);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);

                LayoutInflater inflater=LayoutInflater.from(MainActivity.this);
                View viewDialog=inflater.inflate(R.layout.new_cost_data,null);
                final EditText title=(EditText) viewDialog.findViewById(R.id.et_cost_title);
                final EditText money=(EditText)viewDialog.findViewById(R.id.et_cost_money);
                final DatePicker date=(DatePicker) viewDialog.findViewById(R.id.dp_cost_data);
                builder.setView(viewDialog);
                builder.setTitle("New Cost");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CostBean costBean=new CostBean();
                        costBean.costTitle=title.getText().toString();
                        costBean.costMoney=money.getText().toString();
                        costBean.costDate=date.getYear()+"-"+(date.getMonth()+1)+"-"+date.getDayOfMonth();
                        mdatabaseHelper.insertCost(costBean);
                        mCostBeanList.add(costBean);
                        mAdapter.notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton("Cancel",null);//点击取消
                builder.create().show();//显示dialog的布局
            }
        });
    }

    private void initCostData() {
      // mdatabaseHelper.deleteAllData();
       /* CostBean costBean=new CostBean();
        for (int i=0;i<6;i++) {
            costBean.costTitle=i+"imooc";
            costBean.costDate="11-11";
            costBean.costMoney="20";
            mdatabaseHelper.insertCost(costBean);
        }*/
        Cursor cursor=mdatabaseHelper.getAllCostData();
       if(cursor!=null){
           while(cursor.moveToNext()){
               CostBean costBean1=new CostBean();
               costBean1.costTitle=cursor.getString(cursor.getColumnIndex("cost_title"));
               costBean1.costDate=cursor.getString(cursor.getColumnIndex("cost_date"));
               costBean1.costMoney=cursor.getString(cursor.getColumnIndex("cost_money"));
               mCostBeanList.add(costBean1);
           }
           cursor.close();
       }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_chart) {
            Intent intent=new Intent(MainActivity.this,ChartsActivity.class);
            intent.putExtra("cost_list", (Serializable) mCostBeanList);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

接下来简单的添加一笔帐单的功能已经可以实现,我们来添加一笔账单试试效果。

 

 

 

 

 

 

 

 

 

 (二)开始制作图表

图表的制作我们会用到第三方库hellocharts,具体可以登录该网址查看————https://github.com/lecho/hellocharts-android

接下来在Android Studio中导入该库,在build中的dependencies中导入该github就可以了

 

 

 接下来首先创建一个布局文件,来展示我们的chart图表。

chart_view

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

    <lecho.lib.hellocharts.view.LineChartView
        android:id="@+id/chart"
        android:padding="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

然后再创建一个ChartsActivity.java,再修改主程序中的右上角的内容,在上面主程序的代码中可以看到,就是下面代码,把之前的setting改为chart

public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_chart) {
            Intent intent=new Intent(MainActivity.this,ChartsActivity.class);
            intent.putExtra("cost_list", (Serializable) mCostBeanList);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

更改menu_main中的信息

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.xlfbook.MainActivity">
    <item
        android:id="@+id/action_chart"
        android:orderInCategory="100"
        android:title="Charts"
        app:showAsAction="never" />
</menu>

ChartsActivity.java

package com.example.xlfbook;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.ChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.Chart;
import lecho.lib.hellocharts.view.LineChartView;

public class ChartsActivity extends Activity {

    private LineChartView mChart;
    private Map<String,Integer> table = new TreeMap<>();
    private LineChartData mData;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart_view);
        mChart = (LineChartView) findViewById(R.id.chart);
        mData = new LineChartData();
        List<CostBean> allDate = (List<CostBean>) getIntent().getSerializableExtra("cost_list");

        generateValues(allDate);
        generateData();
    }



    private void generateData() {
        List<Line> lines = new ArrayList<>();
        List<PointValue> values = new ArrayList<>();
        int indexX = 0;
        for(Integer value : table.values()){
            values.add(new PointValue(indexX, value));
            indexX++;
        }
        Line line = new Line(values);
        line.setColor(ChartUtils.COLORS[0]);
        line.setShape(ValueShape.CIRCLE);
        line.setPointColor(ChartUtils.COLORS[1]);
        lines.add(line);
        mData.setLines(lines);
        mChart.setLineChartData(mData);


    }

    private void generateValues(List<CostBean> allDate) {
        if(allDate != null){
            for (int i = 0; i < allDate.size(); i++) {
                CostBean costBean = allDate.get(i);
                String costDate = costBean.costDate;
                int costMoney = Integer.parseInt(costBean.costMoney);
                if(!table.containsKey(costDate)){
                    table.put(costDate,costMoney);
                }else {
                    int originMoney = table.get(costDate);
                    table.put(costDate,originMoney + costMoney);
                }
            }
        }
    }
}

这就是由我们的数据生成的折线图,还有待完善(坐标线还没搞明白怎么添加)

 

 

 

至此,该记账本的简单记账功能以及图表显示功能得以实现。在真机上经过测试,可以使用。

 

 

 

github:https://github.com/happy-xlf/NoteBook

 

posted @ 2020-02-04 13:13  清风紫雪  阅读(6158)  评论(2编辑  收藏  举报