安卓——家庭记账本4

今天完成了支出记录页面的编写,并对数据库插入信息。

首先打开软件进入主界面

 

 下面的两个按钮设置为两个onClick事件

<ImageButton
        android:id="@+id/main_btn_more"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@mipmap/more"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="20dp"
        android:background="@drawable/main_morebtn_bg"/>
    <Button
        android:id="@+id/main_btn_edit"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignBottom="@id/main_btn_more"
        android:background="@drawable/main_record_bg"
        android:layout_toLeftOf="@id/main_btn_more"
        android:text="@string/editone"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:drawableLeft="@mipmap/edit"
        android:gravity="center_vertical"/>
public void onClick(View view){
        switch (view.getId()){
            case R.id.main_iv_search:
                Intent it = new Intent(this,SearchActivity.class);
                startActivity(it);
                break;
            case R.id.main_btn_edit:
                Intent it1 = new Intent(this,RecordActivity.class);
                startActivity(it1);
                break;
            case R.id.main_btn_more:
                MoreDialog moreDialog = new MoreDialog(this);
                moreDialog.show();
                moreDialog.setDialogSize();
                break;
            case R.id.item_mainlv_top_tv_budget:
                showBudgetDialog();
                break;
        }

}

在MainActivity中建立onClick方法,完成点击事件并进行跳转。通过id寻找对应按钮。

接下来,在数据库中定义方法,将数据传入数据库

 /*
    * 读取数据库当中的数据,写入内存集合
    * kind 表示收入或支出
    * */
    public static List<TypeBean> getTypeList(int kind){
        List<TypeBean> list = new ArrayList<>();
        //读取typetb表中的数据
        String sql = "select * from typetb where kind = "+kind;
        Cursor cursor = db.rawQuery(sql,null);
        //循环读取图标内容,存储到对象
        while(cursor.moveToNext()){
            String typename = cursor.getString(cursor.getColumnIndex("typename"));
            int imageId = cursor.getInt(cursor.getColumnIndex("imageId"));
            int simageId = cursor.getInt(cursor.getColumnIndex("simageId"));
            int kind1 = cursor.getInt(cursor.getColumnIndex("kind"));
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            TypeBean typeBean = new TypeBean(id,typename,imageId,simageId,kind);
            list.add(typeBean);
        }


        return list;
    }
/*
    * 向记账表插入一条元素
    * */
    public static void insertItemToAccounttb(AccountBean bean){
        ContentValues values = new ContentValues();
        values.put("typename",bean.getTypename());
        values.put("simageId",bean.getSimageId());
        values.put("beizhu",bean.getBeizhu());
        values.put("money",bean.getMoney());
        values.put("time",bean.getTime());
        values.put("year",bean.getYear());
        values.put("month",bean.getMonth());
        values.put("day",bean.getDay());
        values.put("kind",bean.getKind());
        db.insert("accounttb",null,values);
//        Log.i("animee", "insertItemToAccounttb: ok!!!!!");这是我测试用的,用于检测数据是否传入数据库
    }

做完这些之后,还要配置适配器,最后组装,然后该功能才能实现

配置Account的适配器

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.bookeep.R;
import com.example.bookeep.db.AccountBean;
import java.util.Calendar;
import java.util.List;

public class AccountAdapter extends BaseAdapter {
    Context context;
    List<AccountBean> mDatas;
    LayoutInflater inflater;
    int year,month,day;

    public AccountAdapter(Context context, List<AccountBean> mDatas) {
        this.context = context;
        this.mDatas = mDatas;
        inflater=LayoutInflater.from(context);
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month=calendar.get(Calendar.MONTH)+1;
        day=calendar.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int i) {
        return mDatas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if(view==null){
            view=inflater.inflate(R.layout.item_mainlv,viewGroup,false);
            holder=new ViewHolder(view);
            view.setTag(holder);
        }else {
            holder= (ViewHolder) view.getTag();
        }
        AccountBean bean = mDatas.get(i);
        holder.typeIv.setImageResource(bean.getSimageId());
        holder.typeTv.setText(bean.getTypename());
        holder.beizhuTv.setText(bean.getBeizhu());
        holder.moneyTv.setText("¥"+bean.getMoney());
        if(bean.getYear()==year && bean.getMonth()==month && bean.getDay()==day){
            String time = bean.getTime().split(" ")[0];
            holder.timeTv.setText("今天"+time);
        }else {
            holder.timeTv.setText(bean.getTime());
        }
        return view;
    }

    class ViewHolder{
        ImageView typeIv;
        TextView typeTv,beizhuTv,timeTv,moneyTv;
        public ViewHolder(View view){
            typeIv=view.findViewById(R.id.item_mainlv_iv);
            typeTv=view.findViewById(R.id.item_mainlv_tv_title);
            timeTv=view.findViewById(R.id.item_mainlv_tv_time);
            beizhuTv=view.findViewById(R.id.item_mainlv_tv_beizhu);
            moneyTv=view.findViewById(R.id.item_mainlv_tv_money);
        }
    }
}

设置监听,与适配器进行组装

import android.inputmethodservice.KeyboardView;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.bookeep.R;
import com.example.bookeep.db.AccountBean;

import com.example.bookeep.db.TypeBean;
import com.example.bookeep.utils.BeiZhuDialog;
import com.example.bookeep.utils.KeyBoardUtils;
import com.example.bookeep.utils.SelectTimeDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 记录页面支出模块,BaseRecordFragment
 */
public abstract class OutcomeFragment extends Fragment implements View.OnClickListener {

    KeyboardView keyboardView;
    EditText moneyEt;
    ImageView typeIv;
    TextView typeTv,beizhuTv,timeTv;
    GridView typeGv;
    List<TypeBean> typelist;
    AccountBean accountBean;//将需要插入的数据保存为对象
    TypeBaseAdapter typeBaseAdapter;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;


    public OutcomeFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        accountBean = new AccountBean();//创建对象
        accountBean.setTypename("其他");
        accountBean.setSimageId(R.mipmap.ic_qita_fs);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_outcome, container, false);
        initView(view);
        setInitTime();
        //给GridView填充数据
        loadDataToGV();
        setGVListener();//设置GridView各项的点击事件
        return view;
    }

    //获取当前时间
    private void setInitTime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String time = sdf.format(date);
        timeTv.setText(time);
        accountBean.setTime(time);

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        accountBean.setYear(year);
        accountBean.setMonth(month);
        accountBean.setDay(day);
    }

    //设置GridView各项的点击事件方法
    private void setGVListener() {
        typeGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                typeBaseAdapter.selectPos = i;
                typeBaseAdapter.notifyDataSetChanged();//提示绘制发生变化
                TypeBean typeBean = typelist.get(i);
                String typename = typeBean.getTypename();
                typeTv.setText(typename);
                accountBean.setTypename(typename);
                int simageId = typeBean.getSimageId();
                typeIv.setImageResource(simageId);
                accountBean.setSimageId(simageId);
            }
        });
    }

    public void loadDataToGV() {
        typelist = new ArrayList<>();
        typeBaseAdapter = new TypeBaseAdapter(getContext(), typelist);
        typeGv.setAdapter(typeBaseAdapter);
    }

    public void initView(View view){
        keyboardView=view.findViewById(R.id.frag_record_keyboard);
        moneyEt=view.findViewById(R.id.frag_record_et_money);
        typeIv=view.findViewById(R.id.frag_record_iv);
        typeGv=view.findViewById(R.id.frag_record_gv);
        typeTv=view.findViewById(R.id.frag_record_tv_type);
        beizhuTv=view.findViewById(R.id.frag_record_tv_beizhu);
        timeTv=view.findViewById(R.id.frag_record_tv_time);
        beizhuTv.setOnClickListener(this);
        timeTv.setOnClickListener(this);
        //自定义软键盘显示出来
        KeyBoardUtils boardUtils = new KeyBoardUtils(keyboardView,moneyEt);
        boardUtils.showKey();
        //设置接口,监听确定按钮被点击
        boardUtils.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure() {

                    //获取输入钱数
                String moneyStr = moneyEt.getText().toString();
                if(TextUtils.isEmpty(moneyStr)||moneyStr.equals("0")){
                    getActivity().finish();
                    return;
                }
                float money = Float.parseFloat(moneyStr);
                accountBean.setMoney(money);
//                 获取记录信息,保存在数据库
                    saveAccountToDB();
//                 返回上一级页面
                getActivity().finish();
            }
        });
    }

    public abstract void saveAccountToDB() ;

    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.frag_record_tv_time:
                showTimeDialog();
                break;
            case R.id.frag_record_tv_beizhu:
                showBZDialog();
                break;
        }
    }

    //弹出显示时间的对话框
    private void showTimeDialog() {
        SelectTimeDialog dialog = new SelectTimeDialog(getContext());
        dialog.show();
        //设定确定按钮被点击了
        dialog.setOnEnsureListener(new SelectTimeDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String time, int year, int month, int day) {
                timeTv.setText(time);
                accountBean.setTime(time);
                accountBean.setYear(year);
                accountBean.setMonth(month);
                accountBean.setDay(day);
            }
        });
    }

    //弹出备注对话框
    public void showBZDialog() {
        final BeiZhuDialog dialog = new BeiZhuDialog(getContext());
        dialog.show();
        dialog.setDialogSize();
        dialog.setOnEnsureListener(new BeiZhuDialog.OnEnsureListener() {
            @Override
            public void onEnsure() {
                String msg = dialog.getEditText();
                if(!TextUtils.isEmpty(msg)){
                    beizhuTv.setText(msg);
                    accountBean.setBeizhu(msg);
                }
                dialog.cancel();
            }
        });
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
//    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

做完这些之后,记录支出功能基本完成。

今天测试的时候,在模拟器上程序一直显示停止运行,最后通过Logcat得知在设置监听的时候有个方法错误,我把它注释掉就奇迹般地能运行了,这个方法是AS自动生成的,所以以后尽量少让其自动生成方法。

明天将会完成收入功能及其他功能。

 

posted on 2022-02-03 22:56  跨越&尘世  阅读(97)  评论(0编辑  收藏  举报