大项目一

       

功能需求及技术可行性分析


在开始编码之前,我们需要先对程序进行需求分析,想一想账单中应该具备哪些功能。将这些功能全部整理出来之后,我们才好动手去一一实现。这里我认为掌中账单至少应该具备以下功能。
1.可以选择账目的类型,比如支出和收入以及在往下的分类。
2.可以将个人和公司的账目分开来计。
3.可以选择账目发生的时间,以及相应内容,。
4.可以删除账单。
虽然看上去只有四个主要的功能点,但如果想要全部实现这些功能却需要用到UI、数据存储、服务等技术,因此还是非常考验综合应用能力的。

确定了技术完全可行之后,接下来就可以开始编码了。

布局

首先我想的是布局,先把布局弄好,也就是UI,一个好的UI更具有交互性,更能体现应用的作用,我所设计的布局更为简单化,所谓简而精。应用有两个界面,第一个界面是账单的建立,而第二个界面就是账单明细。
在设计中将线性布局嵌套于相对布局中,使界面更为紧凑。

frm_addbills.xml



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

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/LinearLayout02"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:layout_marginTop="25dip" >

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.85"
                android:minWidth="80dip"
                android:text="选择账目"
                android:textAppearance="?android:attr/textAppearanceLarge" >
            </TextView>

            <EditText
                android:id="@+id/edittext_acctitem"
                android:layout_width="wrap_content"
                android:layout_height="38dp"
                android:layout_weight="0.98"
                android:background="#F0F8FF"
                android:cursorVisible="false"
                android:editable="false"
                android:maxLines="1"
                android:width="200dip" >
            </EditText>
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />

        <LinearLayout
            android:id="@+id/LinearLayout03"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip" >

            <TextView
                android:id="@+id/TextView03"
                android:layout_width="wrap_content"
                android:layout_height="38dp"
                android:layout_weight="0.98"
                android:minWidth="80dip"
                android:text="填入费用"
                android:textAppearance="?android:attr/textAppearanceLarge" >
            </TextView>

            <EditText
                android:id="@+id/Fee"
                android:layout_width="wrap_content"
                android:layout_height="38dp"
                android:layout_weight="0.98"
                android:background="#F0F8FF"
                android:hint="单位:元"
                android:numeric="decimal"
                android:width="200dip" >
            </EditText>
        </LinearLayout>
         <LinearLayout
            android:id="@+id/LinearLayout06"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip" >

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="104dp"
                android:layout_height="38dp"
                android:layout_weight="0.98"
                android:minWidth="80dip"
                android:text="账目类型"
                android:textAppearance="?android:attr/textAppearanceLarge" >
            </TextView>

            <Spinner
                android:id="@+id/Spinner01"
                android:layout_width="194dp"
                android:layout_height="38dp"
                android:layout_weight="12.74"
                android:background="#F0F8FF"
                android:minWidth="200dip" >
            </Spinner>
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />

        <LinearLayout
            android:id="@+id/LinearLayout04"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip" >

            <TextView
                android:id="@+id/TextView02"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#e087CEEB"
                android:drawablePadding="2dip"
                android:fadingEdge="horizontal"
                android:height="24dip"
                android:text="选择时间"
                android:textColor="#e0ffffff" >
            </TextView>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/LinearLayout05"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:layout_marginTop="10dip" 
           >

            <TextView
                android:id="@+id/vdate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:width="120dip" />

            <Button
                android:id="@+id/BtnDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#F0F8FF"
                android:text="C"
                android:textColor="#87CEEB"
                android:textSize="24dip"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/vtime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center_horizontal"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:width="80dip" />

            <Button
                android:id="@+id/BtnTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#F0F8FF"
                android:text="C"
                android:textColor="#87CEEB"
                android:textSize="24dip"
                android:textStyle="bold" />
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />

       

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />

        <TextView
            android:id="@+id/TextView07"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:background="#e087CEEB"
            android:height="24dip"
            android:text="填写备注"
            android:textColor="#e0ffffff" >
        </TextView>

        <EditText
            android:id="@+id/EditTextDESC"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:layout_weight="0.58"
            android:background="#F0F8FF"
            android:gravity="top"
            android:lines="4" >
        </EditText>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />

        <LinearLayout
            android:id="@+id/LinearLayout08"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip" >

            <Button
                android:id="@+id/BtnSave"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#ADD8E6"
                android:text="保 存"
                android:textColor="#ffffff"
                android:textSize="24dip"
                android:textStyle="bold" >
            </Button>

            <Button
                android:id="@+id/BtnCancel"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#ADD8E6"
                android:text="取 消"
                android:textColor="#ffffff"
                android:textSize="24dip"
                android:textStyle="bold" >
            </Button>
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />
    </LinearLayout>

其中, Spinner提供了从一个数据集合中快速选择一项值的办法。默认情况下Spinner显示的是当前选择的值,点击Spinner会弹出一个包含所有可选值的dropdown菜单,从该菜单中可以为Spinner选择一个新值;
layout_margin确定控件距离边界的值,以及控件之间的距离;
layout_weight确定控件的权值,使空间更为紧凑;

grid_bills.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="fill_parent"
    android:background="#87CEEB"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent"
        android:layout_height="470dp"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/layouthead"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:background="#ffCded8b"
            android:clickable="true"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:keepScreenOn="true" >

            <TextView
                android:id="@+id/item1"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:width="20dip" 
                android:textSize="48px"
                android:layout_weight="1"
                android:background="#4682B4"/>

            <TextView
                android:id="@+id/item2"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:text="账目"
                android:gravity="center"
                android:textSize="15dip"
                android:layout_weight="1"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:width="60dip"
                android:background="#4682B4" />

            <TextView
                android:id="@+id/item3"
                android:layout_width="79dp"
                android:layout_height="fill_parent"
                android:background="#4682B4"
                android:gravity="center"
                android:text="费用(元)"
                android:textColor="#ffffff"
                android:textSize="15dip"
                android:textStyle="bold"
                android:width="60dip" />

            <TextView
                android:id="@+id/item4"
                android:layout_width="96dp"
                android:layout_height="fill_parent"
                android:background="#4682B4"
                android:gravity="center"
                android:text="日期"
                android:layout_weight="1"
                android:textColor="#ffffff"
                android:textSize="15dip"
                android:textStyle="bold"
                android:width="80dip" />

            <TextView
                android:id="@+id/item5"
                android:layout_width="116dp"
                android:layout_height="fill_parent"
                android:background="#4682B4"
                android:gravity="center"
                android:text="备注"
                android:textColor="#ffffff"
                android:textSize="15dip"
                android:textStyle="bold"
                android:width="100dip" />

        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="?android:attr/listDivider" />

        <LinearLayout
            android:id="@+id/layout"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:minHeight="372dip" >

            <ListView
                android:id="@+id/listview"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
            </ListView>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/layoutfoot"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#ffCded8b"
            android:layout_marginBottom="10dip" 
            >
           <TextView
                android:id="@+id/item2"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:width="20dip" 
                android:textSize="40px"
                android:background="#4682B4"/>
            <TextView
                android:id="@+id/totalitem"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="当月收入:2009.33 支出:3000.87 小计:-1000.9"
                android:textStyle="bold" 
                android:textColor="#ffffff"
                android:background="#4682B4"/>

        </LinearLayout>
    </LinearLayout>

</ScrollView>

ScrollView滚动视图是指当拥有很多内容,屏幕显示不完时,需要通过滚动跳来显示的视图。ScrollView只支持垂直滚动。 非常有趣;
ListView 用来展示列表的View。

grid_items.xml



<?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="horizontal" >

    <TextView
        android:id="@+id/item1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:width="20dip" 
        android:textColor="#ffffff"/>

    <TextView
        android:id="@+id/item2"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="账目"
        android:layout_weight="1"
        android:width="60dip" 
        android:textColor="#ffffff"/>

    <TextView
        android:id="@+id/item3"
        android:layout_width="42dp"
        android:layout_height="fill_parent"
        android:layout_weight="2.19"
        android:text="费用(元)"
        android:textColor="#ffffff"
        android:textSize="14dip"
        android:textStyle="bold|italic"
        android:width="60dip" />

    <TextView
        android:id="@+id/item4"
        android:layout_width="66dp"
        android:layout_height="fill_parent"
        android:layout_weight="1.63"
        android:text="日期"
        android:textColor="#ffffff"
        android:width="80dip" />

    <TextView
        android:id="@+id/item5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="备注"
        android:textColor="#ffffff"
        android:width="100dip" />

</LinearLayout>
账目,费用,日期和备注,分列排放,这样一来,就相当于形成了一个网格。

活动

先介绍创建活动要用到的方法

Help类:

借助这个类可以非常简单地对数据库创建和升级

CreateTable创建表
try catch可以保证程序的正常运行下去
public class BilldbHelper {

    private static final String TAG = "Cola_BilldbHelper";

    private static final String DATABASE_NAME = "cola.db";
    
    SQLiteDatabase db;
    Context context;
    
    BilldbHelper(Context _context) {
    	context=_context;
    	db=context.openOrCreateDatabase(DATABASE_NAME, 0, null); 
    	Log.v(TAG,"db path="+db.getPath());
    }
    
    public void CreateTable_acctitem() {
    	try{
	        db.execSQL("CREATE TABLE acctitem ("
	                + "_ID INTEGER PRIMARY KEY,"
	                + "PID integer,"
	                + "NAME TEXT"               
	                + ");");
	        Log.v("cola","Create Table acctitem ok");
        }catch(Exception e){
        	Log.v("cola","Create Table acctitem err,table exists.");
        }
    }
    
    public void CreateTable_bills() {
    	try{
	        db.execSQL("CREATE TABLE bills ("
	                + "_id INTEGER primary key autoincrement,"
	                +" acctitemid integer,"   
	                + "fee integer,"
	                + "userid integer,"
	                + "sdate TEXT,"
	                + "stime TEXT,"
	                + "desc TEXT"                
	                + ");");
	        
	        Log.v("cola","Create Table acctitem ok");
        }catch(Exception e){
        	Log.v("cola","Create Table acctitem err,table exists.");
        }
    }
    
    public boolean Bills_save(int acctid,int fee,int userid,String date,String time,String text){
    	String sql="";
    	try{
    		sql="insert into bills values(null,"+acctid+","+fee+","+userid+",'"+date+"','"+time+"','"+text+"')";
	        db.execSQL(sql);
	        
	        Log.v("cola","insert Table bills ok");
	        return true;
	        
        }catch(Exception e){
        	Log.v("cola","insert Table bills err="+sql);
        	return false;
        }
    }
    
    public void CreateTable_colaconfig() {
    	try{
	        db.execSQL("CREATE TABLE colaconfig ("
	                + "_ID INTEGER PRIMARY KEY,"
	                + "NAME TEXT"            
	                + ");");
	        Log.v("cola","Create Table colaconfig ok");
	    }catch(Exception e){
	    	Log.v("cola","Create Table acctitem err,table exists.");
	    }
    }                    
    
    public void CreateTable_users() {
    	try{
	        db.execSQL("Create table tusers (_id integer primary key autoincrement," +
					"caption text not null)");
	        Log.v("cola","Create Table users ok");
	        db.execSQL("insert into tusers values (null,'个人')");
	        db.execSQL("insert into tusers values (null,'公司')");
	    }catch(Exception e){
	    	Log.v("cola","Create Table tusers err,table exists.");
	    }
    }
    
    public void InitAcctitem() {
    	try{
    	  //s.getBytes(encoding);
    	  db.execSQL("insert into acctitem values (1,null,'收入')");
          db.execSQL("insert into acctitem values (2,1,'工资')");
          db.execSQL("insert into acctitem values (9998,1,'其他')");
          db.execSQL("insert into acctitem values (0,null,'支出')");
          db.execSQL("insert into acctitem values (3,0,'生活用品')");
          db.execSQL("insert into acctitem values (4,0,'水电煤气费')");
          db.execSQL("insert into acctitem values (5,0,'汽油费')");
          db.execSQL("insert into acctitem values (9999,0,'其他')");
          
   
          Log.v("cola","insert into ok"); 
    	}catch(Exception e)
    	{
    		Log.v("cola","init acctitem e="+e.getMessage());
    	}
        
    }
    public void Acctitem_newitem(String text,int type){
    	
    	Cursor c =db.query("acctitem", new String[]{"max(_id)+1"}, "_id is not null and _id<9998", null, null, null, null);
    	c.moveToFirst();
    	int maxid=c.getInt(0);    	
    	String sql="insert into acctitem values ("+maxid+","+type+",'"+text+"')";
    	db.execSQL(sql);
    	Log.v("cola","newitem ok text="+text+" id="+type+" sql="+sql);
    	
    }
    
    public void Acctitem_edititem(String text,int id){    	
    	db.execSQL("update acctitem set name='"+text+"' where _id="+id);
    	Log.v("cola","edititem ok text="+text+" id="+id);
    }
    
    public void Acctitem_delitem(int id){
    	
    	db.execSQL("delete from acctitem where _id="+id);
    	Log.v("cola","delitem ok id="+id);
    }
    
    public void QueryTable_acctitem(){
    	
    }
    
    public void FirstStart(){
    	try{
	    	String col[] = {"type", "name" };
	    	Cursor c =db.query("sqlite_master", col, "name='colaconfig'", null, null, null, null);
	    	int n=c.getCount();
	    	if (c.getCount()==0){
	    		CreateTable_acctitem();
	    		CreateTable_colaconfig();
	    		CreateTable_bills();
	    		CreateTable_users();
	    		InitAcctitem();    		
	    	}	    	
	    	//test();	    	
	    	Log.v("cola","c.getCount="+n+"");
	    	    	
	    	
    	}catch(Exception e){
    		Log.v("cola","e="+e.getMessage());
    	}
    	
    	
    }
    
    
    public void close(){
    	db.close();
    }
    
    public Cursor getParentNode(){
    	return db.query("acctitem", new String[]{"_id", "name","pid" }, "pid is null", null, null, null, "pid,_id");    	
  
    }
    
    public Cursor getChildenNode(String pid){
    	Log.v("cola","run getchildenNode");
   		return db.query("acctitem", new String[]{"_id", "name" }, "pid="+pid, null, null, null, "_id");    	

    }
   
    public Cursor getUserid(){
    	Log.v("cola","run get users cursor");
   		return db.query("tusers", new String[]{"_id", "caption" }, null, null, null, null, null);    	

    }
    
    public Cursor getBills(String date){
    	Log.v("cola","run get bills cursor date="+date);
   		return db.query("bills a,acctitem b", new String[]{"a._id _id","a.rowid rowid", "acctitemid","b.name name","b._id bid","( case when pid=0 then '-' else '' end)||fee/100||'' fee","sdate||' '||stime sdate","desc" }, "a.acctitemid=b._id and a.sdate like '"+date+"%'", null, null, null, null);    	

    }
    
    public void delBills(int id)
    {
    	db.execSQL("delete from bills where _id="+id);
    }
    
    public String getBillsTotal(String date){
    	Log.v("cola","run get bills total cursor");
   		Cursor cur=db.query("bills a,acctitem b", new String[]{"sum(case when b.pid=0 then -fee end)/100||'' out","sum(case when b.pid=1 then fee end)/100||'' infee","sum(case when b.pid=0 then -fee else fee end)/100||'' total"}, "a.acctitemid=b._id and a.sdate like '"+date+"%'",null, null, null, null);    	
   		cur.moveToFirst(); 
   		String s="";
	    while(!cur.isAfterLast()){
	    	
	    	s="当月收入:"+cur.getFloat(1)+" 元"+"  支出:"+cur.getFloat(0)+" 元"+"  小计:"+cur.getFloat(2);
	    	cur.moveToNext(); 
	    }
	    return s;
    }
    
    public String test(){
    	try{    		    	   
    		Cursor c2 =getUserid();
    		String ss="";  
    		c2.moveToFirst(); 
    	    while(!c2.isAfterLast()){
    	    	
    	    	ss = c2.getString(0) +", "+ c2.getString(1);
    	    	
    	    	
    	    	c2.moveToNext(); 
    	    	
    	    	Log.v("cola","ss="+ss+"");
    		}
    	    	
    	    return ss;
    	}catch(Exception e){
    		Log.v("cola","e="+e.getMessage());
    		return "err";
    	}
    }


}

添加账单类

Frm_Addbills.java
主要添加了关于创建账单的方法,包括对事件的监听,数据的刷新、传送与储存,向下一界面的跳转等等
public class Frm_Addbills extends Activity implements OnClickListener {

	EditText edittext_acctitem,EditTextDESC,Fee;
	TextView mDate;
	TextView mTime;
	static final int RG_REQUEST = 0;
	
	private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;

    Spinner s1;
    Button BtnDate,BtnTime;  
    Button BtnCancel,BtnSave;
    
    BilldbHelper billdb;
    
    int acctitemid=-1;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setTitle("ColaBox-添加账单");		
		setContentView(R.layout.frm_addbills);
		
		edittext_acctitem = (EditText)findViewById(R.id.edittext_acctitem);		
		edittext_acctitem.setOnClickListener(this);
		
		EditTextDESC=(EditText)findViewById(R.id.EditTextDESC);	
		Fee=(EditText)findViewById(R.id.Fee);	
		
		BtnDate=(Button)findViewById(R.id.BtnDate);
		BtnDate.setOnClickListener(this);
		BtnTime=(Button)findViewById(R.id.BtnTime);
		BtnTime.setOnClickListener(this);
		
		BtnCancel=(Button)findViewById(R.id.BtnCancel);
		BtnCancel.setOnClickListener(this);
		BtnSave=(Button)findViewById(R.id.BtnSave);
		BtnSave.setOnClickListener(this);
		
		mDate = (TextView) findViewById(R.id.vdate);
        mTime = (TextView) findViewById(R.id.vtime);
		
		//Calendar c=Calendar.getInstance(Locale.CHINA);
		initTime();
        
        
        
        setDatetime();
        billdb = new BilldbHelper(this);
        s1=(Spinner) findViewById(R.id.Spinner01);        
        String[] from= new String[]{"caption"};
        int[] to=new int[]{android.R.id.text1};
        Cursor cur=billdb.getUserid();     
        SimpleCursorAdapter mAdapter=new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, cur,from, to);      
        mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);           
        s1.setAdapter(mAdapter);
     
        //getBillsTotal
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 0, "账目明细").setIcon(R.drawable.editbills);
		menu.add(0, 4, 0, "退 出").setIcon(R.drawable.quit);
		menu.add(0, 5, 0, "关于ColaBox");	
		return true;
	}

	public void onClick(View v) {
		if (v.equals(edittext_acctitem)) {
			Log.v("ColaBox", "cmd=edittext_acctitem");
			//test
			Editor sharedata = getSharedPreferences("data", 0).edit();
			sharedata.putString("item","hello getSharedPreferences");
			sharedata.commit();
			
			Intent intent = new Intent();
			intent.setClass(Frm_Addbills.this, Frm_Editacctitem.class);			
			startActivityForResult(intent, RG_REQUEST);
		} else if (v.equals(BtnTime)){
			showDialog(1);
		} else if (v.equals(BtnDate)){
			showDialog(2);
		} else if (v.equals(BtnCancel)){
			cancel();
		} else if (v.equals(BtnSave)){
			save();
		}
		
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Intent intent = new Intent();
			intent.setClassName(Frm_Addbills.this,"com.cola.ui.Grid_bills");;
			startActivity(intent);
			return true;
		case 2:
			
			int nOrientation = getRequestedOrientation();  
			if (nOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)  
			  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
			else  
			  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			    
			return true;
		case 3:
			 Intent i = new Intent(); 
             i.setClass(Frm_Addbills.this, LocalService.class); 
             ComponentName compName = startService(i); 
             if (compName == null) 
             { 
                     Log.e("main_Service", "startService() failed!"); 
             } 
			//startService(new Intent(Frm_Addbills.this,mainService.class));
			return true;
		case 4:
			QuitApp();
			return true;
		case 5:
			  new AlertDialog.Builder(this) 
			    .setTitle("ColaBox") 
			    .setMessage("versions1") 
			    .show();
			return true;
		}
		return false;
	}

    
    
	public void QuitApp() {
		new AlertDialog.Builder(Frm_Addbills.this).setTitle("提示").setMessage(
				"确定退出?").setIcon(R.drawable.quit).setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {	
						billdb.close();
						finish();
					}
				}).setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				}).show();

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RG_REQUEST) {
			if (resultCode == RESULT_CANCELED) {
			
			} else if (resultCode == RESULT_OK) {
				edittext_acctitem.setText((String) data.getCharSequenceExtra("name"));
				acctitemid=Integer.parseInt((String)data.getCharSequenceExtra("id"));
				Log.v("cola","get acctitemid="+acctitemid);
				
			}
		}
	}
	
	private void cancel(){
		Log.v("cola","u put cancel btn");
		edittext_acctitem.setText("");
		Fee.setText("");
		acctitemid=-1;
		initTime();setDatetime();
		EditTextDESC.setText("");
	}
	private void save(){
		Log.v("cola","u put save btn");
		if (acctitemid==-1){
			new AlertDialog.Builder(this)
			    .setMessage("请首先选择账目.")
			    .show();
			return;
		}
		int fee=0;
		String s=Fee.getText().toString();
		int pos=s.indexOf(".");
		if (pos>0){	
			if (s.length()-pos<3){
				s=s+"0";
			}
			fee=Integer.parseInt(s.substring(0,pos)+s.substring(pos+1,pos+3));		
		}else{			
		    fee=Integer.parseInt(s)*100;
			
		}
		Log.v("cola","u put save btn");		
		if (billdb.Bills_save(acctitemid,fee,(int)s1.getSelectedItemId(), ((TextView)mDate).getText().toString(), ((TextView)mTime).getText().toString(),EditTextDESC.getText().toString())){
			Toast.makeText(this, "保存成功.", Toast.LENGTH_SHORT).show(); 
			cancel();
		}else{
			Toast.makeText(this, "保存失败,请检查数据.", Toast.LENGTH_SHORT).show(); 
		}
	}

    
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			QuitApp();
			return true;
			
		}
		return false;
	}
	private void initTime(){
		Calendar c = Calendar. getInstance(TimeZone.getTimeZone("GMT+08:00"));
		mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH)+1;
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
	}
	
	private void setDatetime(){
		mDate.setText(mYear+"-"+mMonth+"-"+mDay);
        mTime.setText(pad(mHour)+":"+pad(mMinute));
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 1:
                return new TimePickerDialog(this,
                        mTimeSetListener, mHour, mMinute, false);
            case 2:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth-1, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case 1:            	
                ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
                break;
            case 2:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth-1, mDay);
                break;
        }
    }    
	
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear+1;
                mDay = dayOfMonth;

                setDatetime();
            }
        };

    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                setDatetime();
            }
        };
    private static String pad(int c) {
            if (c >= 10)
                return String.valueOf(c);
            else
                return "0" + String.valueOf(c);
        }        
}

账单明细

Frm_Editacctitem.java
public class Frm_Editacctitem extends ExpandableListActivity {
	private int mGroupIdColumnIndex;

	
	private ExpandableListAdapter mAdapter;

	BilldbHelper billdb;

	Dialog_edit newdialog;
	
	


	private ExpandableListContextMenuInfo info;

	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("ColaBox-选择账目");
		billdb = new BilldbHelper(this);

		
		Cursor groupCursor = billdb.getParentNode();
		mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow("_ID");
		mAdapter = new MyExpandableListAdapter(groupCursor, this,
				android.R.layout.simple_expandable_list_item_1,
				android.R.layout.simple_expandable_list_item_1,
				new String[] { "NAME" }, 
				new int[] { android.R.id.text1 }, new String[] { "NAME" }, //
				new int[] { android.R.id.text1 });
		setListAdapter(mAdapter);
		registerForContextMenu(getExpandableListView());

		//test
		SharedPreferences sharedata = getSharedPreferences("data", 0);
		String data = sharedata.getString("item", null);
	    Log.v("cola","data="+data);
		
	}
	
    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
    {
    	Bundle bundle = new Bundle();
    	bundle.putString("name", ((TextView)v).getText().toString());//给bundle 写入数据
    	bundle.putString("id", id+"");
    	
    	Intent mIntent = new Intent();
    	mIntent.putExtras(bundle);
    	setResult(RESULT_OK, mIntent);
    	billdb.close();
    	finish(); 

    	return true;	
    }
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateOptionsMenu(menu);
		if (ExpandableListView
				.getPackedPositionType(((ExpandableListContextMenuInfo) menuInfo).packedPosition) == 1) {
			Log.v("cola", "run menu");
			menu.setHeaderTitle("菜单");
			menu.add(0, 1, 0, "新 增");
			menu.add(0, 2, 0, "删 除");
			menu.add(0, 3, 0, "编 辑");
		}

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		info = (ExpandableListContextMenuInfo) item.getMenuInfo();

		if (item.getItemId() == 1) {
			
			newdialog = new Dialog_edit(this, "请输入新增账目的名称", "",
					mDialogClick_new);
			newdialog.show();
		} else if (item.getItemId() == 2) {
			new AlertDialog.Builder(this).setTitle("提示").setMessage("确定要删除'"+((TextView)info.targetView).getText().toString()+"'这个账目吗?")
					.setIcon(R.drawable.delete).setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									billdb.Acctitem_delitem((int)info.id);
									updatedisplay();
								}
							}).setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									// 取消按钮事件
								}
							}).show();

		} else if (item.getItemId() == 3) {
			newdialog = new Dialog_edit(this, "请修改账目名称",
					((TextView) info.targetView).getText().toString(),
					mDialogClick_edit);
			newdialog.show();
		}

		return false;
	}

	private Dialog_edit.OnDateSetListener mDialogClick_new = new Dialog_edit.OnDateSetListener() {
		public void onDateSet(String text) {
			Log.v("cola", "new acctitem");
			billdb.Acctitem_newitem(text,ExpandableListView.getPackedPositionGroup(info.packedPosition));
			updatedisplay();
		}

	};
	
	private Dialog_edit.OnDateSetListener mDialogClick_edit = new Dialog_edit.OnDateSetListener() {
		public void onDateSet(String text) {			
			billdb.Acctitem_edititem(text,(int)info.id);
			updatedisplay();
		}

	};

	private void updatedisplay(){
		Log.v("cola", "update display");
		((MyExpandableListAdapter)mAdapter).notifyDataSetChanged();

	}
	
	public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {

		public MyExpandableListAdapter(Cursor cursor, Context context,
				int groupLayout, int childLayout, String[] groupFrom,
				int[] groupTo, String[] childrenFrom, int[] childrenTo) {
			super(context, cursor, groupLayout, groupFrom, groupTo,
					childLayout, childrenFrom, childrenTo);
		}

		@Override
		protected Cursor getChildrenCursor(Cursor groupCursor) {

			String pid = groupCursor.getLong(mGroupIdColumnIndex) + "";
			return billdb.getChildenNode(pid);

		}

		@Override
		public long getGroupId(int groupPosition) {
			Cursor groupCursor = (Cursor) getGroup(groupPosition);
			return groupCursor.getLong(mGroupIdColumnIndex);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			Cursor childCursor = (Cursor) getChild(groupPosition, childPosition);
			return childCursor.getLong(0);
		}

	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值