网络111 刘修军
本例子简单了解Buutton、TextView、EditText、对话框的用法。
功能:计算圆的面积,当输入非数字时,会弹出一个提示框,提示用户输入数字。
<?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="vertical" > <EditText android:id="@+id/inputR" android:layout_width="match_parent" android:layout_height="wrap_content" > <requestFocus /> </EditText> <TextView android:id="@+id/circleArea" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <Button android:id="@+id/compute" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>
import java.text.DecimalFormat; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class CircleAreaActivity extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); inputR=(EditText) findViewById(R.id.inputR); circleArea=(TextView) findViewById(R.id.circleArea); compute=(Button) findViewById(R.id.compute); compute.setOnClickListener(this); } EditText inputR; TextView circleArea; Button compute; @Override public void onClick(View arg0) { // TODO Auto-generated method stub try { float area,r; r=Float.parseFloat(inputR.getText().toString()); area=(float) (Math.PI*r*r); //圆的面积 DecimalFormat de=new DecimalFormat("0.00"); // 格式转换 circleArea.setText(de.format(area).toString()); } catch(Exception e) { AlertDialog.Builder alert=new AlertDialog.Builder(this); alert.setTitle("提示"); alert.setMessage("非数字字符,请输入数字!"); alert.setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub inputR.setText("");// 清空EditTExt } }); alert.show(); //显示对话框 } } }