Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Android开发学习(9)记忆功能计算器

$
0
0

承接上篇博客,每到一个阶段,我们就用一个项目总结我们学习到的内容,今天我们就一起继续完成一个拥有记忆功能的简单计算器,首先我们先看下计算器布局:

布局

计算主页面:

calc_main

历史记录查询页面:

calc_history

自定义标题:

head.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_titlebar"
                android:layout_width="match_parent"
                android:layout_height="52dp"
                android:background="#ed4255" >

    <Button
            android:id="@+id/button_backward"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:background="#ed4255"
            android:drawablePadding="6dp"
            android:ellipsize="end"
            android:onClick="back"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:singleLine="true"
            android:text="&lt; 返回"
            android:textColor="#ffffffff"
            android:textSize="20dp"
            android:visibility="visible" />

    <TextView
            android:id="@+id/text_title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:ellipsize="marquee"
            android:gravity="center_horizontal|center"
            android:singleLine="true"
            android:text="XS-APP"
            android:textColor="#ffffffff"
            android:textSize="20dp" />



    <Button
            android:id="@+id/button_forward"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:drawablePadding="6dp"
            android:background="#ed4255"
            android:ellipsize="end"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:singleLine="true"
            android:text="···"
            android:textColor="#ffffffff"
            android:textSize="30dp"
            android:visibility="invisible" />

</RelativeLayout>

计算器主页面:

calc.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:background="#fafcfa"
              android:layout_height="match_parent">


    <include layout="@layout/head" />

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <TextView
                android:id="@+id/print_show"
                android:layout_width="0dp"
                android:layout_height="@dimen/view_size_150"
                android:layout_weight="1"
                android:background="@color/background_head"
                android:gravity="left"
                android:padding="@dimen/view_space_10"
                android:textSize="@dimen/font_size_20" />



    </LinearLayout>


    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <Button
                android:id="@+id/key_C"
                style="@style/keyStyle"
                android:text="C" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_clean"
                style="@style/keyStyle"
                android:text="清除" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />
        <Button
                android:id="@+id/key_hisrory"
                style="@style/keyStyle"
                android:text="历史" />

    </LinearLayout>


    <View
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size_.5"
            android:background="@color/white" />

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <Button
                android:id="@+id/key_7"
                style="@style/keyStyle"
                android:text="7" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_8"
                style="@style/keyStyle"
                android:text="8" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_9"
                style="@style/keyStyle"
                android:text="9" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_div"
                style="@style/keyStyle"
                android:text="÷" />
    </LinearLayout>

    <View
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size_.5"
            android:background="@color/white" />

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <Button
                android:id="@+id/key_4"
                style="@style/keyStyle"
                android:text="4" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_5"
                style="@style/keyStyle"
                android:text="5" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_6"
                style="@style/keyStyle"
                android:text="6" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_mul"
                style="@style/keyStyle"
                android:text="x" />
    </LinearLayout>

    <View
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size_.5"
            android:background="@color/white" />

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <Button
                android:id="@+id/key_1"
                style="@style/keyStyle"
                android:text="1" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_2"
                style="@style/keyStyle"
                android:text="2" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_3"
                style="@style/keyStyle"
                android:text="3" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_sub"
                style="@style/keyStyle"
                android:text="-" />
    </LinearLayout>

    <View
            android:layout_width="wrap_content"
            android:layout_height="@dimen/line_size_.5"
            android:background="@color/white" />

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <Button
                android:id="@+id/key_point"
                style="@style/keyStyle"
                android:text="." />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_0"
                style="@style/keyStyle"
                android:text="0" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_print"
                style="@style/keyStyle"
                android:text="=" />

        <View
                android:layout_width="@dimen/line_size_.5"
                android:layout_height="match_parent"
                android:background="@color/white" />

        <Button
                android:id="@+id/key_add"
                style="@style/keyStyle"
                android:text="+" />
    </LinearLayout>

</LinearLayout>

计算器历史记录页面:

calc_history.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">

    <include layout="@layout/head" />

    <!--list父窗口 -->
    <ListView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/LV_Calc">
    </ListView>

</LinearLayout>

calc_history_item.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">

    <TextView
            android:text="TextView01"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:id="@+id/item_calc"
            android:textSize="20dip">
    </TextView>

</LinearLayout>

Activity

计算器

package com.xvshu.android;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.xvshu.android.db.CalcHisrory;
import com.xvshu.android.db.SqliteManage;
import com.xvshu.android.service.HelloService;

import java.util.Stack;


/**
 * Created by xvshu on 2017/7/26.
 */
public class CalcActivity extends Activity {

    private TextView printTv = null;
    //声明两个参数。接收tvResult前后的值
    double num1=0,num2=0;

    int op=0;//判断操作数,
    boolean isClickEqu=false;//判断是否按了“=”按钮


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calc);
        printTv=(TextView) findViewById(R.id.print_show);
    }

    public void keyClick(View v) {
        String sbcalc=printTv.getText().toString();
        System.out.println(sbcalc);
        if (v == null) return;
        if (printTv.getText().toString().indexOf("=")>=0) {
            System.out.println("hava = ");
            sbcalc="";
        }
        switch (v.getId()) {
            case R.id.key_clean:
                System.out.println("R.id.key_clean");
                sbcalc="";
                break;
            case R.id.key_C:
                System.out.println("R.id.key_C");
                try {
                    sbcalc=sbcalc.substring(0, sbcalc.length()-1);
                } catch (Exception e) {
                    sbcalc="";
                }
                break;
            case R.id.key_hisrory:
                System.out.println("R.id.key_hisrory");
                showCalcHistory();
                return;
            default:
                break;
        }

        switch (v.getId()) {
            case R.id.key_0:
                System.out.println("R.id.key_0");
                if (sbcalc.toString().length() != 0) {
                    sbcalc+="0";
                }
                break;
            case R.id.key_1:
                System.out.println("R.id.key_1");
                sbcalc+="1";
                break;
            case R.id.key_2:
                System.out.println("R.id.key_2");
                sbcalc+="2";
                break;
            case R.id.key_3:
                System.out.println("R.id.key_3");
                sbcalc+="3";
                break;
            case R.id.key_4:
                System.out.println("R.id.key_4");
                sbcalc+="4";
                break;
            case R.id.key_5:
                System.out.println("R.id.key_5");
                sbcalc+="5";
                break;
            case R.id.key_6:
                System.out.println("R.id.key_6");
                sbcalc+="6";
                break;
            case R.id.key_7:
                System.out.println("R.id.key_7");
                sbcalc+="7";
                break;
            case R.id.key_8:
                System.out.println("R.id.key_8");
                sbcalc+="8";;
                break;
            case R.id.key_9:
                System.out.println("R.id.key_9");
                sbcalc+="9";
                break;
            case R.id.key_point:
                System.out.println(" . ");
                if (sbcalc.length() != 0)
                    sbcalc+=".";
                break;

            //加减乘除
            case R.id.key_add:
                System.out.println(" + ");
                sbcalc+=" + ";
                break;

            case R.id.key_sub:
                System.out.println(" - ");
                sbcalc+=(" - ");
                break;
            case R.id.key_mul:
                System.out.println(" x ");
                sbcalc+=(" x ");
                break;
            case R.id.key_div:
                System.out.println(" ÷ ");
                sbcalc+=(" ÷ ");
                break;
            case R.id.key_print:
                System.out.println(" = ");
                sbcalc=(sbcalc+"="+compute(sbcalc));
                addHistroy(sbcalc);
                break;
            default:
                break;
        }
        printTv.setText(sbcalc);
    }

    private String compute(String input)//即1237 的 样例
    {
        String str[];
        str = input.split(" ");
        Stack<Double> s = new Stack<Double>();
        double m = Double.parseDouble(str[0]);
        s.push(m);
        for(int i=1;i<str.length;i++)
        {
            if(i%2==1)
            {
                if(str[i].compareTo("+")==0)
                {
                    double help = Double.parseDouble(str[i+1]);
                    s.push(help);
                }

                if(str[i].compareTo("-")==0)
                {
                    double help = Double.parseDouble(str[i+1]);
                    s.push(-help);
                }

                if(str[i].compareTo("x")==0)
                {
                    double help = Double.parseDouble(str[i+1]);
                    double ans = s.peek();//取出栈顶元素
                    s.pop();//消栈
                    ans*=help;
                    s.push(ans);
                }

                if(str[i].compareTo("÷")==0)
                {
                    double help = Double.parseDouble(str[i+1]);
                    double ans = s.peek();
                    s.pop();
                    ans/=help;
                    s.push(ans);
                }
            }
        }
        double ans = 0d;
        while(!s.isEmpty())
        {
            ans+=s.peek();
            s.pop();
        }
        String result = String.valueOf(ans);
        return result;
    }

    private void addHistroy(String calcValue){
        ContentValues valuesIn = new ContentValues();
        valuesIn.put(CalcHisrory.calcValueName, calcValue);
        SqliteManage.getInstance(this).insertItem(CalcHisrory.TableName, valuesIn);
    }

    public void showCalcHistory(){
        Intent intent_calc = new Intent(this, CalcHistoryActivity.class);
        startActivity(intent_calc);
    }
    public void back(View view){
        this.finish();
    }

}

历史记录

package com.xvshu.android;

import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.xvshu.android.db.CalcHisrory;
import com.xvshu.android.db.SqliteManage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;


/**
 * Created by xvshu on 2017/7/26.
 */
public class CalcHistoryActivity extends Activity {

    private ListView lvCalc;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calc_history);
        lvCalc=(ListView) findViewById(R.id.LV_Calc);
        showCalchistory();
    }

    private void showCalchistory(){
        List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>();
        SqliteManage.QueryResult result = SqliteManage.getInstance(this).query(CalcHisrory.TableName, null, null);
        List<String> historys =new ArrayList<String>();
        while (result.cursor.moveToNext()) {
            historys.add(result.cursor.getString(result.cursor.getColumnIndex(CalcHisrory.calcValueName)));
        }
        if(historys!=null && historys.size()>0){
            for(String one : historys){
                HashMap<String,Object> item=new HashMap<String, Object>();
                item.put("item_calc",one);
                data.add(item);
            }
        }
        SimpleAdapter adapter=new SimpleAdapter(this,data,R.layout.calc_history_item,
                new String[]{"item_calc"},new int[]{R.id.item_calc});

        lvCalc.setAdapter(adapter);
    }

    public void back(View view){
        this.finish();
    }

}

Sqlite

SqliteManage.java

package com.xvshu.android.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import java.io.File;

/**
 * Created by 22762 on 2016/1/7.
 */
public class SqliteManage {
    private static SqliteManage mInstance;
    private File mFile;

    private SqliteManage(Context context) {
        String path;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "AndroidXS";
        } else {
            path = context.getFilesDir() + File.separator + "data";
        }
        boolean success = new File(path).mkdirs();
        mFile = new File(path, "data.db");

        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mFile, null);
        db.execSQL("create table if not exists "+CalcHisrory.TableName+"(_id INTEGER PRIMARY KEY AUTOINCREMENT,"+CalcHisrory.calcValueName+" varchar(500))");
        db.close();
    }

    public static SqliteManage getInstance(Context context) {
        if (mInstance == null) {
            synchronized (SqliteManage.class) {
                if (mInstance == null) {
                    mInstance = new SqliteManage(context);
                }
            }
        }
        return mInstance;
    }

    public boolean isExitInTable(String table, String where, String[] args) {
        boolean flag = false;
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mFile, null);
        Cursor cursor = db.query(table, null, where, args, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            flag = true;
        }
        cursor.close();
        db.close();
        return flag;
    }

    public boolean insertItem(String table, ContentValues cv) {
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mFile, null);
        if (db.insert(table, null, cv) == 1) {
            db.close();
            return true;
        }
        db.close();
        return false;
    }

    public boolean delteItem(String table, String where, String[] args) {
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mFile, null);
        int i = db.delete(table, where, args);
        db.close();
        if (i > 0) return true;
        return false;
    }

    public boolean updateItem(String table, String where, String[] args, ContentValues values) {
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mFile, null);
        int i = db.update(table, values, where, args);
        db.close();
        if (i > 0) return true;
        return false;
    }

    public QueryResult query(String table, String where, String[] args) {
        QueryResult queryResult = new QueryResult();
        queryResult.db = SQLiteDatabase.openOrCreateDatabase(mFile, null);
        queryResult.cursor = queryResult.db.query(table, null, where, args, null, null, null);
        return queryResult;
    }

    public class QueryResult {
        public SQLiteDatabase db;
        public Cursor cursor;
    }
}

CalcHisrory.java

package com.xvshu.android.db;

/**
 * Created by xvshu on 2017/8/10.
 */
public class CalcHisrory {
    public final static String TableName="calc_history";
    public final static String calcValueName="calc_value";
}

总结

安卓的开发,越来越感觉非常便捷,感到安卓大行其道的原因,开发方便应该是一大助力!我们用一个小的项目打个节点,希望大家跟上节奏,我们继续探索移动开发中的秘密。

源码下载:记忆功能计算器

作者:xvshu 发表于2017/8/11 10:31:32 原文链接
阅读:0 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>