2012年4月12日 星期四

[Android]Button 及 Toast 使用範例



<ButtonToast.java>
   1: package com.android.buttontoast;
   2:  
   3: import android.app.Activity;
   4: import android.os.Bundle;
   5: import android.view.View;
   6: import android.widget.Button;
   7: import android.widget.Toast;
   8:  
   9: public class ButtonToast extends Activity {
  10:     /** Called when the activity is first created. */
  11:     @Override
  12:     public void onCreate(Bundle savedInstanceState) {
  13:         super.onCreate(savedInstanceState);
  14:         setContentView(R.layout.main);
  15:         
  16:         Button btnPressMe = (Button) findViewById(R.id.pressmeBtn);
  17:         Button btnExit = (Button) findViewById(R.id.exitBtn);
  18:         
  19:         btnPressMe.setOnClickListener(new Button.OnClickListener(){
  20:             public void onClick(View v) {
  21:                 Toast.makeText(    ButtonToast.this,
  22:                                 "ButtonToast 程式執行成功!",
  23:                                 Toast.LENGTH_LONG).show();
  24:             } 
  25:         });
  26:         
  27:         btnExit.setOnClickListener(new Button.OnClickListener(){
  28:             public void onClick(View v) {
  29:                 android.os.Process.killProcess(android.os.Process.myPid());
  30:             } 
  31:         });
  32:     }
  33: }

<main.xml>
   1: <?xml version="1.0" encoding="utf-8"?>
   2: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   3:     android:layout_width="fill_parent"
   4:     android:layout_height="fill_parent"
   5:     android:orientation="horizontal" >
   6:  
   7:     <Button
   8:         android:id="@+id/pressmeBtn"
   9:         android:layout_width="wrap_content"
  10:         android:layout_height="wrap_content"
  11:         android:text="@string/strPressMe" />
  12:  
  13:     <Button
  14:         android:id="@+id/exitBtn"
  15:         android:layout_width="wrap_content"
  16:         android:layout_height="wrap_content"
  17:         android:text="@string/strExit" />
  18:  
  19: </LinearLayout>

<strings.xml>
   1: <?xml version="1.0" encoding="utf-8"?>
   2: <resources>
   3:  
   4:     <string name="hello">Hello World, ButtonToast!</string>
   5:     <string name="app_name">ButtonToast</string>
   6:     <string name="strPressMe">請按我</string>
   7:     <string name="strExit">離開</string>
   8:  
   9: </resources>

沒有留言:

張貼留言