2012年7月3日 星期二

Android:Checkbox

XML layout




 <CheckBox
                android:id="@+id/checkBox1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="紅茶" />

   <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="一杯20"
            android:inputType="number" >

 <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="總額" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="計算" />

Source Code

package com.wu;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

public class Checkbox2Activity extends Activity {
    /** Called when the activity is first created. */
CheckBox che;
EditText edi;
TextView tex;
Button but;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        che=(CheckBox)findViewById(R.id.checkBox1);
        edi=(EditText)findViewById(R.id.editText1);
        tex=(TextView)findViewById(R.id.textView1);
        but=(Button)findViewById(R.id.button1);
        che.setOnCheckedChangeListener(
        new OnCheckedChangeListener(){
                        //boolean isChecked用來判斷該CheckBox是否有被按下
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub

if(isChecked){
edi.setEnabled(true);
}else{
tex.setText("");
edi.setEnabled(false);
}
}
       
        });
        but.setOnClickListener(
        new OnClickListener(){

public void onClick(View arg0) {
// TODO Auto-generated method stub
double num=0;
num=Double.parseDouble(edi.getText().toString());
tex.setText(String.format("一共是%f元", num*20));
}
       
        });
     
    }
}












沒有留言:

張貼留言