天天看點

Android常用控件總結

 .

Notepad++編寫  可以負責粘貼到其中去 看得更清楚。(内容包括了Android中的大部分常用控件及其事件的監聽)

第一章

 1.1  Android中src檔案夾包含項目的所有包及其資源檔案,res檔案夾包含了項目中所有的資源。比如:程式圖示(drawable),布局檔案(layout),常量(value),音頻檔案(raw)

    R.java是在建立項目是自動生成的隻讀檔案,不可更改此檔案。R檔案其作用:是定義項目中所有資源的索引檔案。

 1.2  AndroidManfest.xml 如下:

   <?xml version="1.0" encoding="utf-8"?>

   <manifest               //根節點,描述了packege包中所有的内容

    xmlns:android="http://schemas.android.com/apk/res/android" //包命名空間的聲明,使得Android中各種标準屬性能在檔案中使用,提供了大部分元素中的資料

    package="Android.Summary"         //引用程式包名

    android:versionCode="1"

    android:versionName="1.0">

   <uses-sdk android:minSdkVersion="7" />       //使用SDK版本号

   <application             //包含package中application級别元件聲明的根節點,可包含application的一些全局和預設的屬性,如标簽label,icon,主題,必要的全限。注意:一個manifest中隻能包含一個或0個application

    android:icon="@drawable/icon"         //應用程式圖示

    android:label="@string/app_name">       //應用程式名字

     <activity android:name=".SummaryActivity"    //Activity用來與使用者互動的主要工具,是使用者打開程式的初始界面.此處為引用程式預設啟動的Activity

       android:label="@string/app_name">

    <intent-filter>/           //描述了Activity的啟動時間和位置,另外為了支援查找Activity可以包含一個或多個<intent-filter>

                <action android:name="android.intent.action.MAIN" />  //acton 為元件支援的Intent action

                <category android:name="android.intent.category.LAUNCHER" />//categor 為元件支援的Intent category 這裡指定了引用程式的預設啟動的Activity

    </intent-filter>

   </activity>

    <activity android:name = "Activity02"></activity>   //在此對新增的Activity進行注冊。如果在不同的包中注意聲明是将包名帶上

   </application>

   </manifest>

 1.3  String.xml如下:

   <?xml version="1.0" encoding="utf-8"?>

   <resources>              //此處定義了兩個字元串資源,即定義了app_name,hello常量

    <string name="hello">Hello World, SummaryActivity!</string>

    <string name="app_name">Summary</string>

   </resources>

   如何使用這個資源呢?如下:

   Resources r = this.getContext().getResources();     //通過Context的getResource()執行個體化一個Resources對象

   String app_name = ((String)r.getString(R.string.app_name));  //然後通過getString()方法取得指定的索引的字元串。項目中所有常量都可以在String.xml檔案中定義

   String hello = ((String)r.getString(R.string.hello));

 1.4  main.xml如下:

   <?xml version="1.0" encoding="utf-8"?>

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"//LinearLayout 線程版面配置

    android:orientation="vertical"        //版面配置的方式。此為自上到下為垂直配置,"horizontal"為水準配置

    android:layout_width="fill_parent"       //定義目前視圖在螢幕上所占的寬度,"fill_parent"為填充整個螢幕寬度

             //用于給一個布局中多個視圖的重要度指派

    android:layout_height="fill_parent"       //定義目前視圖在螢幕上所占的高度,...........................高度

    >

    <TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"       //随着視圖的欄位的不同而改變這個視圖的高度或寬度

    android:text="@string/hello"        //在視圖上顯示的内容,此處引用了@String中的hello字元串

    />

   </LinearLayout>

 1.5  src下的java 如下:

   package Android.Summary;

   import android.app.Activity;

   import android.os.Bundle;

   public class SummaryActivity extends Activity {     //繼承自Activity

   @Override

    public void onCreate(Bundle savedInstanceState){   //重寫onCreate()方法

      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);      //設定要顯示的布局

    }

   }

第二章

 2.1  Android應用程式由四個子產品組成:Activity,Service,Intent,ContentProvider(注意:一個應用程式不一定包含全部的四個子產品).

   在使用時必須在AandroidManfest中進行聲明。

    Activity可以了解為使用者看到螢幕,主要用于處理應用程式的整體性工作。如:

     a.監聽系統事件,觸屏事件,為使用者顯示指定的View,啟動其他Activity等。

     b.所有應用的Activity都繼承于android.app.Activity,該類是Android提供的基層類。

     c.一個Activity通常就是一個單獨的螢幕。

     d.每一個活動都被實作為一個獨立的類。

     e.大多數的應用程式都是由多個Activity組成。

     Intent Aandroid中主要用Intent類實作從一個Activity跳轉到另一個Activity。在Intent的描述結構中,有兩個重要的部分:動作和對應的資料。

     典型的動作有MAIN,VIEW,PICK,EDIT.而動作對應的資料則以URI的形式表示。例如:要查一個人的聯系方式,需要建立一個動作類型View的Intent

     ,以及一個表示這個人的URI.

     Intent的使用:

     button1.setOnClickListener(new Button.OnClickListener(){

      public void onClick(View v){

        Intent intent = new Intent();   //建立一個Intent對象

        intent.setClass(Activity01.this,Activity02.class);//指明要啟動的另一Activity02

        startActivity(intent);     //啟動一個新的Activity

        Activity01.this.finish();    //關閉目前Activity01

      }

     });

     這裡需要注意在Android中對新啟動的Activity進行聲明。聲明方式:

     <activity android:name = "Activity02"></activity>  //注意:如果在不同的包中在聲明是還要加上包名

     IntentReceiver                                

      如果希望Android應用能夠對外部事件(如電話打入時,資料網絡可用時,)做出響應,可用使用IntentReceiver.雖然IntentReceiver在如上事件發生

     時會使用NotificationManager通知使用者,但它并不能生産UI。IntentReceiver可以在AndroidManifest.xml中注冊,也可在代碼中使用Context.registerReceiver

     進行注冊。當IntentReceiver被觸發時,系統會在需要的時候啟動應用。各種應用還可以通過ContentReceiver()将他們自己的IntentReceiver廣播出去。   ???????

    Content Provider

     作用:主要用于不同應用程式中的資料的傳遞。

       Content Provider 是一個特殊的存儲資料的類型。

       Android自身提供現成的Content Provider:Contacts ,Browser,CallLog,Settings,MediaStore

       應用可用通過唯一的ContentResolver界面來使用具體的Conten Provider,然後可以用ContentResolver提供的方法來使用你需要的Content Provider

      其中,ContentResolver提供的方法有query(),insert(),update()等。

       URI----String形式的Content Provider的完整路徑。

     下面這個這個例子通過ContentProvider擷取電話本中的資料,然後顯示到TextView中去。

     public class Activity01 extends Activity{

      public void onCreate(Bundle savedInstanceState){

       TextView textView = new TextView(this);//得到TextView對象

       String string = "";

       super.onCreate(savedInstanceState);

       ContentResolver resolver = getContentResolver();//得到ContentResolver對象

       Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);//取得電話本中開始一項的光标,通過query方法查詢出符合标準的電話本記錄

        //向下移動光标

        while(cursor.moveToNext()){

        //取得聯系人名字

        int name_index = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);

        String name = cursor.getString(name_index);

        //取得電話号碼

        int number_index = cursor.getColumnIndex(PhoneLookup.NUMBER);

        String number = cursor.getString(number_index);

        string +=(name+":"+number+"\n");

        }

        cursor.close();

        textView.setText(string);//設定TextView顯示的内容

        setContentView(textView);//顯示到螢幕上 其實TextView也是View的一種

       }

      }

     注意:在使用這些子產品中用到了讀取聯系人的API,是以必須在AndroidManifest.xml中聲明

      聲明方式為:

       <uses_permission

        android:name="android.permission.READ_CONTACTS">

       </uses-permission>

    Service 背景服務,沒有界面

     啟動service方法:

      a.Context.startService()

      b.Context.bindService()//與上一種方法不同處 如果這個Service沒有處于啟動狀态,則将其啟動

     下面這個例子以Activity中的倆個控件來控制播放一首Mp3. (例中:需要在res檔案夾中建立一個raw檔案夾 然後放入一首MP3)

     public class Activity01 extends Activity{

      public void onCreate(Bundle savedInstanceState){

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

      //從main.xml布局中獲得Button對象

      Button button_start = (Button)findViewById(R.id.start);

      Button button_stop = (Button)findViewById(R.id.stop);

      //設定按鈕(Button)監聽

      button_start.setOnClickListener(start);

      button_stop.setOnClickListener(stop);

      }

       //開始按鈕

      private OnClickListener start = new OnClickListener(){

       public void onClick(View v){  

       //開啟Service

       startService(new Intent("com.yarin.Android.MUSIC"));

       }

      };

       //停止按鈕

      private OnClickListener stop = new OnClickListener(){

       public void onClick(View v){

       //停止Service

       stopService(new Intent("com.yarin.Android.MUSIC"));      

       }

      };

      }

     public class MusicService extends Service{

      //MediaPlayer對象

      private MediaPlayer player;

      public IBinder onBind(Intent arg0){

       return null;

       }

      public void onStart(Intent intent, int startId){

       super.onStart(intent, startId);

       //這裡可以了解為裝載音樂檔案

       player = MediaPlayer.create(this, R.raw.test);

       //開始播放

       player.start();

       }

      public void onDestroy(){

       super.onDestroy();

       //停止音樂-停止Service

       player.stop();

       }

      }

     AndroidManifest.xml檔案中

     <service android:name=".MusicService">

      <intent-filter>

       <action android:name="com.yarin.Android.MUSIC" />

       <category android:name="android.intent.category.default" />

      </intent-filter>

     </service>

 2.2  Aandrod的生命周期 

     public class Activity02 extends Activity{

      private static final String TAG = "Activity02";

      public void onCreate(Bundle savedInstanceState){

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main2);

       Log.v(TAG, "onCreate");

      }

      public void onStart(){

       super.onStart();

       Log.v(TAG, "onStart");

      }

      public void onResume(){

       super.onResume();

       Log.v(TAG, "onResume");

      }

      public void onPause(){

       super.onPause();

       Log.v(TAG, "onPause");

      }

      public void onStop(){

       super.onStop();

       Log.v(TAG, "onStop");

      }

      public void onDestroy(){

       super.onDestroy();

       Log.v(TAG, "onDestroy");

      }

      public void onRestart(){

       super.onRestart();

       Log.v(TAG, "onReStart");

      }

     }

    這些方法都是系統自動調用的。

第三章

 3.1  事件處理

   * 控件事件通過設定其控件的監聽器來監聽并處理事件

   * 按鍵按下事件:通過重寫onKeyDown方法

   * 按鍵彈起事件:通過重寫onKeyUp方法

   * 觸筆點選事件:通過實作onTouchEvent方法

   * 示例中使用了Toast控件:

    * Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

     public class Activity01 extends Activity{

      public void onCreate(Bundle savedInstanceState){

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

      //獲得Button對象

      Button button_ok = (Button) findViewById(R.id.ok);

      button_ok.setOnClickListener(new Button.OnClickListener() {-------------------------------------------------------//設定Button控件監聽器

       public void onClick(View v){

      //這裡處理事件

        DisplayToast("點選了OK按鈕");

        }

       });

      }

      public boolean onKeyDown(int keyCode, KeyEvent event){

       switch (keyCode){

        case KeyEvent.KEYCODE_DPAD_CENTER:

         DisplayToast("按下:中鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_UP:

         DisplayToast("按下:上方向鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_DOWN:

         DisplayToast("按下:下方向鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_LEFT:

         DisplayToast("按下:左方向鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_RIGHT:

         DisplayToast("按下:右方向鍵");

         break;

        }

       return super.onKeyDown(keyCode, event);

       }

      public boolean onKeyUp(int keyCode, KeyEvent event){

       switch (keyCode){

        case KeyEvent.KEYCODE_DPAD_CENTER:

         DisplayToast("彈起:中鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_UP:

         DisplayToast("彈起:上方向鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_DOWN:

         DisplayToast("彈起:下方向鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_LEFT:

         DisplayToast("彈起:左方向鍵");

         break;

        case KeyEvent.KEYCODE_DPAD_RIGHT:

         DisplayToast("彈起:右方向鍵");

         break;

        } 

       return super.onKeyUp(keyCode, event);

       }

      //用于響應按鍵重複點選,官方API指出onKeyMultiple方法總是傳回false,即它沒有handle,是以必須重寫才能實作-------------------此方法沒用過具體情況怎麼樣不是很清楚?

      public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event){

       return super.onKeyMultiple(keyCode, repeatCount, event);

       }

      public boolean onTouchEvent(MotionEvent event){

       int iAction = event.getAction();  //利用getAction得到所執行的動作

       if (iAction == MotionEvent.ACTION_CANCEL ||

         iAction == MotionEvent.ACTION_DOWN ||

          iAction == MotionEvent.ACTION_MOVE){

        return false;

        }

      //得到觸筆點選的位置

       int x = (int) event.getX();

       int y = (int) event.getY();

                //将獲得的坐标轉成String類型的方法

        DisplayToast("觸筆點選坐标:("+Integer.toString(x)+","+Integer.toString(y)+")");

       return super.onTouchEvent(event);

      }

      public void DisplayToast(String str){

       Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

       }

      }

   我們分析了一些常用事件處理方式。每一個鍵都對應一個鍵值。當然也可根據需要來改變一些鍵的功能,需要我們自己建構KeyEvent對象------------------有待進一步學習

   構造KeyEvent對象的幾種方法:

       KeyEvent(int action,int code);

    KeyEvent(long DownTime,long EventTime,int action,int code,int repeat);

    KeyEvent(long DownTime,long EventTime,int action,int code,int repeat,int metState);

    KeyEvent(long DownTime,long EventTime,int action,int code,int repeat,int metState,int device,int scancode);

    KeyEvent(long DownTime,long EventTime,int action,int code,int repeat,int metState,int device,int scancode,int flags);

    KeyEvent(KeyEvent origEvent,long EventTime,int newRepart);

     例:

     public class Activity01 extends Activity{

      public void onCreate(Bundle savedInstanceState){

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

      }

      public boolean onKeyDown(int keyCode, KeyEvent event){

       //這裡建構KeyEvent對象,其功能為傳回鍵的功能

       //是以我們按任意鍵都會執行傳回鍵功能

      KeyEvent key = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);

       //這裡傳入的參數就是我們自己建構的KeyEvent對象key

      return super.onKeyDown(key.getKeyCode(), key);

      }

     }

 3.2  常用控件

   Button

    xml設計

      <Button

       android:id="@+id/button"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       ></Button>

    代碼設計 Button button = new Button(this);

       button.setText("我是Button");

       button.setWidth(123);  //設定寬度

       button.setHeight(123); //設定高度

       button.setTextColor(Color.BLUE); //設定文字顔色

       button.setTextSize(123);   //設定字型大小

       button.setBackgroundColor(Color.BLUE);  //設定控件背景色

    監聽器    

      button.setOnClickListener(new Button.OnClickListener(){//設定按鈕的事件監聽

       public void onClick(View v){

       //處理按鈕事件産生一個Toast.利用button.getText()得到按鈕顯示的内容

       Toast toast = Toast.makeText(Activity01.this, "你點選了“"+button.getText()+"”按鈕!", Toast.LENGTH_LONG);

       //設定toast顯示的位置

       toast.setGravity(Gravity.TOP, 0, 150);

       //顯示該Toast

       toast.show();

       }

      });

   -----------------------------------------------------------------------------------------------------------------------------

   TextView 一個用來顯示文本的控件

    xml設計 <TextView

       android:id= "@+id/textView"       //設定id

       android:layout_width ="fill_parent"  //寬度充滿全屏

       android:layout_height="wrap_content" //高度随控件變化

       android:layout_height="2dip"

       android:textColor=""

       android:background="#aaa00" //背景顔色

       android:text="你好"/>

       android:paddingLeft="50px"

       android:paddingTop="5px"

       android:paddingBottom="5px"

       android:textSize="30sp"

       android:singleLine="true"

       android:layout_below="@id/imageView_handler"//在什麼下

       android:gravity ="left"  //用于設定View中内容相對于View元件的對齊方式,

       android:layout_gravity//用于設定View元件相對于Container的對齊方式。

       android:paddingLeft="30px" // 按鈕上設定的内容離按鈕左邊邊界30個像素

       android:layout_marginLeft="30px"  //整個按鈕離左邊設定的内容30個像素

       android:layout_weight="1"//控件權重 即占的比例 預設值為0

       android:gravity="center_horizontal"//水準居中

       android:padding="3dip"

    代碼設計 TextView textView = new TextView(this); //聲明對象

       textView.setTextColor(Color.RED);  //設定字型顔色

       textView.setTextSize(20);    //設定字型大小

       textView.setBackgroundColor(Color.BLUE);//控件背景色

       textView.setText("你好")    //顯示的文字

       textView.setHeight

       textView.setWidth

       textView.setVisibility(GONE/VISIBLE); //設定為不可見/可見

       textView.setGravity(Gravity.CENTER);//設定文字權重

    監聽器 TextView textView = new TextView(this);  //得到對象

      textview.setOnClickListener(new TextView.OnClickListener(){-------------------------------------------TextView監聽器

       public void onClick(View v){

       }

      });

   -------------------------------------------------------------------------------------------------------------------------------

   ImageButton 帶圖示的按鈕

    xml設計

      <ImageButton 

       android:id= "@+id/imageButton1"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:src="@drawable/qq"   //在xml設計所使用的圖檔

      />

    代碼中設計

      imageButton.setImageDrawable(getResources().getDrawable(R.drawable.image2));//在代碼中設計使用的圖檔(得到對象後)

    監聽器

      imageButton.setOnClickListener(new Button.OnClickListener() {---------------------------------------------ImageButton監聽器

       @Override

       public void onClick(View v) {

        //建立對話框

        Dialog dialog = new AlertDialog.Builder(ImageButton_Dialog.this)

         .setTitle("ImageButton2")

         .setMessage("跳轉到系統圖檔")

         .setPositiveButton("确定", new DialogInterface.OnClickListener() {    

          @Override

          public void onClick(DialogInterface dialog, int which) {

          // TODO Auto-generated method stub

          imageButton2.setImageDrawable(getResources().getDrawable(android.R.drawable.sym_action_call));

          }

         }).create();

         dialog.show();

       }

      });

   -------------------------------------------------------------------------------------------------------------------------------

   EditText

    xml設計

      <EditText

       android:id="@+id/editText"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:textSize="18sp"

       android:layout_x="29px"

       android:layout_y="33px"

       android:hint="請輸入賬号" //設定當m_EditText中為空時提示的内容

       />

    代碼設計 EditText editText = new EditText(this);//得到EditText對象

       editText.setTextSize(20);  //設定字型大小

       editText.setHint("請輸入賬号");  //設定當m_EditText中為空時提示的内容

    監聽器

      editText.setOnKeyListener(new EditText.OnKeyListener(){-----------------------------------------EditText監聽器

       @Override

       public boolean onKey(View arg0, int arg1, KeyEvent arg2){

        // 得到文字,将其顯示到TextView中

        m_TextView.setText("文本框中内容是:" + m_EditText.getText().toString());

        return false;

       }

      });

   -----------------------------------------------------------------------------------------------------------------

   CheckBox 多項選擇 需要對沒有按鈕設定監聽器

    xml設計

     <CheckBox

      android:id="@+id/checkBox"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="@string/CheckBox4"

     >

    監聽器    

     checkBox1.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {//對每個選項設定事件監聽-------------------CheckBox監聽器

     @Override

      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){

       if(m_CheckBox1.isChecked()){

         DisplayToast("你選擇了:"+m_CheckBox1.getText());

       }

      }

     });

   -------------------------------------------------------------------------------------------------------------------

   Spinner 下拉清單

    下面一個例子将可選内容通過ArrayAdapter和下拉清單連接配接起來。設定監聽器 通過setVisibility方法設定目前顯示項

    main.xml

     <?xml version="1.0" encoding="utf-8"?>

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

      android:orientation="vertical"

      android:layout_width="fill_parent"

      android:layout_height="fill_parent"

      >

      <TextView 

       android:id="@+id/TextView1"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:text="@string/hello"

      />

      <Spinner

       android:id="@+id/Spinner1"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_centerHorizontal="true"

      />

     </LinearLayout>

     public class Activity01 extends Activity{

      private static final String[] string = { "O型", "A型", "B型", "AB型", "其他" };

      private TextView    m_TextView;

      private Spinner     m_Spinner;

      private ArrayAdapter<String> adapter;

      @Override

      public void onCreate(Bundle savedInstanceState){

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

       m_TextView = (TextView) findViewById(R.id.TextView1);

       m_Spinner = (Spinner) findViewById(R.id.Spinner1);

       //将可選内容與ArrayAdapter連接配接

       adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, string);

       //設定下拉清單的風格

       adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

       //将adapter添加到m_Spinner中

       m_Spinner.setAdapter(adapter);

       //添加Spinner事件監聽

       m_Spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {--------------------------Spinner監聽器

        @Override

         public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){

         m_TextView.setText("你的血型是:" + string[arg2]);

         //設定顯示目前選擇的項

         arg0.setVisibility(View.VISIBLE);

         }

        @Override

        public void onNothingSelected(AdapterView<?> arg0){

         // TODO Auto-generated method stub

         }

        );

       }

      }

     }

   ------------------------------------------------------------------------------------------------------

   RadioGroup , RadioButton 單選選擇控件

    一個單選選擇由兩部分組成,分别是前面的選擇按鈕和後面的内容。按鈕通過RadioButton來實作,答案通過RadioGroup來實作

   如果确定是選擇哪一項那就要設定監聽器setOnCheckedChangeListener.

    下面有一例子:本例中使用到了String.xml檔案來定義常量。

   string.xml

    <?xml version="1.0" encoding="utf-8"?>

     <resources>

      <string name="hello">Android底層是基于什麼作業系統?</string>

      <string name="app_name">Examples_04_07</string>

      <string name="RadioButton1">Windows</string>

      <string name="RadioButton2">Linux</string>

      <string name="RadioButton3">Moc os</string>

      <string name="RadioButton4">Java</string>

     </resources>

   main.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     >

     <TextView 

      android:id="@+id/TextView01"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="@string/hello"

     />

     <RadioGroup

      android:id="@+id/RadioGroup01"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:orientation="vertical"

      android:layout_x="3px"

      android:layout_y="54px"

      >

      <RadioButton

       android:id="@+id/RadioButton1"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="@string/RadioButton1"

      />

      <RadioButton

       android:id="@+id/RadioButton2"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="@string/RadioButton2"

      />

      <RadioButton

       android:id="@+id/RadioButton3"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="@string/RadioButton3"

      />

      <RadioButton

       android:id="@+id/RadioButton4"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="@string/RadioButton4"

      />

     </RadioGroup>   

    </LinearLayout>

    public class Activity01 extends Activity{

     TextView  m_TextView;

     RadioGroup  m_RadioGroup;

     RadioButton  m_Radio1, m_Radio2, m_Radio3, m_Radio4;

     @Override

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);

      m_RadioGroup = (RadioGroup) findViewById(R.id.RadioGroup01);//獲得RadioGroup對象

      m_Radio1 = (RadioButton) findViewById(R.id.RadioButton1);//獲得4個RadioButton對象

      m_Radio2 = (RadioButton) findViewById(R.id.RadioButton2);

      m_Radio3 = (RadioButton) findViewById(R.id.RadioButton3);

      m_Radio4 = (RadioButton) findViewById(R.id.RadioButton4);

     m_RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {---------------------------RadioGroup監聽器

      @Override

      public void onCheckedChanged(RadioGroup group, int checkedId){

       if (checkedId == m_Radio2.getId()){

        DisplayToast("正确答案:" + m_Radio2.getText() + ",恭喜你,回答正确!");

       }else{

        DisplayToast("請注意,回答錯誤!");

        }

       }

      });

     }

     public void DisplayToast(String str)//顯示Toast{

      Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);

       //設定toast顯示的位置

       toast.setGravity(Gravity.TOP, 0, 220);

       //顯示該Toast

       toast.show();

     }

    }

   -----------------------------------------------------------------------------------------------------------

   AutoCompletTextView 和 MultiAutoCompleteTextView 作用:自動提示   下面例中用到了ArrayAdapter

   autoCompletTextView.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     >

     <AutoCompleteTextView 

      android:id= "@+id/autoCompleteTextView"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

     />

     <MultiAutoCompleteTextView 

      android:id= "@+id/multiAutoCompleteTextView"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

     />

    </LinearLayout>

   //如何實作如果輸入的字元不在其範圍内的也能得到提示  是繼承TextWatcher?

    public class Control_Auto extends Activity {

       //implements TextWatcher{}

     public TextView textView_auto;

     private static final String[] string ={"ni hao","ni hao ","ni hao ma","ni zheng de hao ma","nshis"};

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState); 

      setContentView(R.layout.autocompletetextview);

       //将可選内容與擴充卡ArrayAdapter連接配接

      ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,string);

      MultiAutoCompleteTextView multiAutoCompletTextView = (MultiAutoCompleteTextView)findViewById(R.id.multiAutoCompleteTextView);

      AutoCompleteTextView autoCompleteTextView =(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);

      autoCompleteTextView.setAdapter(adapter); //将adapter添加到AutoCompletTextView中去

      multiAutoCompletTextView.setAdapter(adapter); //将adapter添加到MultAutoCompleteTextView中去

      multiAutoCompletTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

     }

    }

    public class Gallery_BaseAdapter extends Activity{

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.gallery);

      Gallery gallery = (Gallery)findViewById(R.id.gallery1);//擷取Gallery對象

      gallery.setAdapter(new Gallery_Adapter(this));//将Gallery_Adapter添加到Gallery對象中去

      gallery.setBackgroundResource(R.drawable.bj);//設定Gallery背景

      //設定監聽事件

      gallery.setOnItemClickListener(new OnItemClickListener() {--------------------------------------------------------Gallery監聽器

       @Override

       public void onItemClick(AdapterView<?> arg0, View v, int position,

          long arg3) {

       // TODO Auto-generated method stub

       Toast.makeText(Gallery_BaseAdapter.this, "你選擇了"+(position+1)+"号圖檔", Toast.LENGTH_LONG)

       .show();

       }  

      });

     }

    }

   ==========================================================================================================================

   ImageSwitcher  切換圖檔

    ImageSwitcher類必須設定一個ViewFactory,主要用來将顯示的圖檔和父視窗區分開,所有要實作ViewSwitcher.ViewFactory接口,通過makeView()

    方法來顯示圖檔,這裡會傳回一個ImageView對象,在通過setImageResource用來顯示指定的圖檔資源。

    public class ImageSwitch_LinearLayout extends Activity implements ViewFactory, OnClickListener{

     private static final int BUTTON_DWON_ID = 1;//下一頁按鈕ID  注意此處數組1,2,3我是随便取的此處還不是很清楚

     private static final int BUTTON_UP_ID = 2;//上一頁按鈕ID

     private static final int SWITCH_ID =3;//ImageSwitch對象的ID

     private static int index = 0;//設定圖檔資源數組的索引

     ImageSwitcher imageSwitcher;

     private static final Integer[] integer ={//所要顯示的圖檔資源數組

        R.drawable.t1,

        R.drawable.t2,

        R.drawable.t3,

        R.drawable.t4,

        R.drawable.t5,

        R.drawable.t6,

     };

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      LinearLayout linearLayout = new LinearLayout(this);//建立一個線性布局

      linearLayout.setOrientation(LinearLayout.VERTICAL);

       imageSwitcher = new ImageSwitcher(this);//建立一個ImageSwitcher對象

       linearLayout.addView(imageSwitcher);//線上性布局中添加imageSwitcher視圖

       imageSwitcher.setId(SWITCH_ID);//為ImageSwitcher對象設定Id

        //為imageSwitcher對象設定資料源

       imageSwitcher.setFactory(this);

       imageSwitcher.setImageResource(integer[index]);

       setContentView(linearLayout);//設定顯示上面建立的線性布局

       Button button1 = new Button(this);//建立上一頁按鈕

        button1.setId(BUTTON_UP_ID);

        button1.setText("上一頁");

        button1.setOnClickListener(this);//創立監聽器

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100,100);//設定Button按鈕的寬 ,高

        params.gravity = Gravity.CENTER;//設定控件的相對螢幕的布局 ,不是控件中的文字相對控件的布局

        linearLayout.addView(button1,params);//将button1 加入到線性布局中去

       TextView textView1 = new TextView(this);

        textView1.setId(BUTTON_DWON_ID);

        textView1.setText("下一頁");

        textView1.setGravity(Gravity.CENTER);//設定文字權重

        textView1.setBackgroundColor(Color.RED);

        textView1.setTextColor(Color.BLUE);

       textView1.setOnClickListener(this);

       LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(100,100);

         params2.gravity = Gravity.CENTER;//設定控件的相對螢幕的布局 ,不是控件中的文字相對控件的布局

         linearLayout.addView(textView1,params2);

     }

     @Override

     public View makeView() {

      // TODO Auto-generated method stub

      return new ImageView(this);//将所有圖檔通過ImageView來顯示

     }

     @Override

     public void onClick(View view) {

      // TODO Auto-generated method stub

      switch(view.getId()){

       case BUTTON_UP_ID:

        index ++;

        if(index>=integer.length){

         index = 0;

        }

        imageSwitcher.setImageResource(integer[index]);//用此方法顯示指定圖檔

        break;

       case BUTTON_DWON_ID:

        index --;

        if(index<=0){

         index = integer.length-1;

        }

        imageSwitcher.setImageResource(integer[index]);

        break;

       default:

        break;

      }

     }

    }

   =======================================================================================================================

   GridView 網格視圖

    當有多個元素要顯示時,就需要使用BaseAdapter來存儲。

    <?xml version="1.0" encoding="utf-8"?>

    <GridView xmlns:android="http://schemas.android.com/apk/res/android"

     android:id="@+id/gridview1"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     android:numColumns="auto_fit"

     android:verticalSpacing="10dp"

     android:horizontalSpacing="10dp"

     android:columnWidth="90dp"

     android:stretchMode="columnWidth"

     android:gravity="center"

    />

    public class GridView_BaseAdapter extends BaseAdapter{

   * BaseAdapter繼承自Adapter為Android中用到基礎資料擴充卡,主要用途是将一組資料傳到ListView,

   * Gallery,Spinner,GridView等UI顯示元件,其中getView是将擷取後的元件View傳回給UI,如ListView每一行

   * 中TextView,以及Gallery中的每個ImageView。BaseAdapter相當于資料源與UI中的橋梁

     private Context context;//定義context  後面有解釋  具體意思不是很清楚?

      private Integer[] tId={

       R.drawable.t1,

       R.drawable.t2,

       R.drawable.t3,

       R.drawable.t4,

       R.drawable.t5,

       R.drawable.t6,

       R.drawable.t7,

       R.drawable.t8,

      };

      //聲明Gallery_Adapter

     public GridView_BaseAdapter(Context context){//構造器

      this.context=context;

     }

     @Override

     public int getCount() {//擷取圖檔的個數

      // TODO Auto-generated method stub

      return tId.length;

     }

     @Override

     public Object getItem(int position) {//擷取圖檔在數組中位置

      // TODO Auto-generated method stub

      return position;

     }

     @Override

     public long getItemId(int position) {//擷取圖檔在數組中位置

      // TODO Auto-generated method stub

      return position;

     }

     @Override

     public View getView(int position, View convertView, ViewGroup parent) {

      // TODO Auto-generated method stub

      ImageView imageView;

      if(convertView ==null){//判斷原來View是否為空 ,如果為空就建立 如果不為空就把原來的轉為自己的View

       imageView = new ImageView(context);

        //注意:此行代碼一加就會出現錯誤。原因是LayoutParams是對上一層控件的設定(即對父控件的設定),而此處ImageView已經是最上層控件了。

        //imageView.setLayoutParams(new Gallery.LayoutParams(80,80));//設定布局圖檔以80*80顯示

        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);//設定顯示比例類型

      }else{

        imageView = (ImageView)convertView;

      }

      imageView.setImageResource(tId[position]);//給ImageView設定資源

       return imageView;//傳回資料庫中的imageView資源給UI

     }

    }

    public class GridView_Adapter extends Activity{

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.gridview_baseadapter);

      GridView gridView12 = (GridView)findViewById(R.id.gridview1);

      gridView12.setAdapter(new GridView_BaseAdapter(this));//添加元素到gridView中去

      gridView12.setBackgroundResource(R.drawable.yj);//設定Gallery背景色

      gridView12.setOnItemClickListener(new OnItemClickListener(){-----------------------------------------------------------GridView監聽器

       @Override

       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,

            long arg3){

         // TODO Auto-generated method stub

        Toast.makeText(GridView_Adapter.this, "你選擇了"+arg2+"号圖檔按鈕",Toast.LENGTH_LONG ).show();

       }  

      });

     }

    }

   ====================================================================================================================================================

   ScrollView 卷軸視圖

    是指當擁有的很多内容,一屏顯示不完時,需要通過滾動來顯示視圖。(如文字過長時)。下面這個例子當我們點選Button時自動産生多個類似項,如果一屏顯示不完,則

    通過ScrollView來顯示。

    scrollview.xml

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

     android:id="@+id/scrollView1"

     android:layout_width="fill_parent"

     android:layout_height="wrap_content"

     android:scrollbars="none">

     <LinearLayout

      android:id="@+id/linearLayout_ScrollView"

      android:orientation="vertical"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content">

     <TextView

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="TextView0"/>

     <Button

      android:id="@+id/button_ScrollView"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="Button0"/>

     </LinearLayout>

    </ScrollView>

   * 問題:下面注釋掉的部分沒了解  注釋掉得部分是為了實作循環滾動  ,但出現了問題?

   * ScrollView是在螢幕顯示不下的時候出現滾動條,但注意不要在ScrollView中放多個元件,否則會出現

   * ERROR/AndroidRuntime(271): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

   * (ScrollView隻能包裹一個直接子元素)

    public class Scroll_View extends Activity{

     public ScrollView scrollView1;

     public LinearLayout linearLayout_ScrollView;

     public Button button01;

     public Handler handler = new Handler();//使用Handler來更新布局高度,即跳轉到新增的控件中去

     public int index = 1;

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.scrollview);

      scrollView1 = (ScrollView)findViewById(R.id.scrollView1);

      linearLayout_ScrollView = (LinearLayout)findViewById(R.id.linearLayout_ScrollView);

      button01 = (Button)findViewById(R.id.button_ScrollView);

       //設定監聽器

      button01.setOnClickListener(button02);

      //button01.setOnKeyListener(N);//改變預設焦點

     }

     public Button.OnClickListener button02 = new Button.OnClickListener(){

      @Override

      public void onClick(View v) {

       // TODO Auto-generated method stub

       EditText editText = new EditText(Scroll_View.this);

       editText.setText("NI HAO"+index++);

       LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(

          LinearLayout.LayoutParams.FILL_PARENT,

          LinearLayout.LayoutParams.WRAP_CONTENT);

       linearLayout_ScrollView.addView(editText,params);

       //editText.setOnKeyListener(M);//設定監聽,改名預設焦點切換

       handler.post(msg);//投遞一個消息

      }

     };

     public Runnable msg = new Runnable(){------------------------------------------------------------------------Runnable的使用

      public void run(){

      //此處作用是是螢幕跳到新加的一行當中去

      //例如:如果新加一個EditText,運作效果就向上滾動一個EditText的寬度,如果超出整

      //個螢幕N個EditText 就了解為螢幕最下方顯示新增加的第N+1個EditText 依次向上為N,N-1

      //N-2,N-3。而原來的第一個已不可見

      int off = linearLayout_ScrollView.getMeasuredHeight()-scrollView1.getHeight();

       if(off>0){

        scrollView1.scrollTo(0,off);

       }

      }

     };

     // public View.OnKeyListener M = new View.OnKeyListener() {//事件監聽

     // 

     //  @Override

     //  public boolean onKey(View v, int keyCode, KeyEvent event) {

     //   // TODO Auto-generated method stub

     //   if(keyCode ==KeyEvent.KEYCODE_DPAD_DOWN&&

     //     event.getAction() == KeyEvent.ACTION_DOWN&&

     //     v == linearLayout_ScrollView.getChildAt(linearLayout_ScrollView.getChildCount()-1)){

     //    findViewById(R.id.button1).requestFocus();

     //   }

     //   return false;

     //  }

     // };

     // public View.OnKeyListener N = new View.OnKeyListener() {

     // 

     //  @Override

     //  public boolean onKey(View v, int keyCode, KeyEvent event) {

     //   // TODO Auto-generated method stub

     //   View view = null;

     //   if(event.getAction()== KeyEvent.ACTION_DOWN){

     //    int A = linearLayout_ScrollView.getChildCount();

     //    switch(keyCode){

     //    case KeyEvent.KEYCODE_DPAD_UP:

     //     if(A>0){

     //      view = linearLayout_ScrollView.getChildAt(A-1);

     //     }

     //     break;

     //    case KeyEvent.KEYCODE_DPAD_DOWN:

     //     if(A<linearLayout_ScrollView.getWeightSum()){

     //      view = linearLayout_ScrollView.getChildAt(A);

     //     }

     //     break;

     //     default:

     //      break;

     //    }

     //   }

     //   if(view !=null){

     //    view.requestFocus();

     //    return true;

     //   }else{

     //    return false;

     //   }

     //  }

     // };

    }

   =======================================================================================================================================

   ProgressBar 進度條

   progressbar.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     >

     <Button

      android:id="@+id/button_bar"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="打開progressbar"

     />

     <ProgressBar

      android:id="@+id/progressbar01"

      android:layout_width="300dp"

      android:layout_height="wrap_content"

      android:visibility="gone"

      style="?android:attr/progressBarStyleHorizontal"//長形進度條

     />

     <ProgressBar

      android:id="@+id/progressbar02"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:max="100"

      android:secondaryProgress="70"

      android:progress="50"

      android:visibility="gone"

      style="?android:attr/progressBarStyleLarge"//圓形進度條

     />

    </LinearLayout>

   * 本例有一個問題如何使标題欄中的進度條在走完後 變為不可現?

    public class ProgressBar_Handler extends Activity{

     public ProgressBar progressbar01;

     public ProgressBar progressbar02;

     public Button button_bar;

     public int count = 0;

     public static final int   STOP  = 0;

     public static final int  CURRENT = 1;

    public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      requestWindowFeature(Window.FEATURE_PROGRESS);//設定視窗模式,因為需要顯示進度條在标題欄

      setProgressBarVisibility(true);

      setContentView(R.layout.progressbar);

      progressbar01 = (ProgressBar)findViewById(R.id.progressbar01);

      progressbar02 = (ProgressBar)findViewById(R.id.progressbar02);

      button_bar = (Button)findViewById(R.id.button_bar);

      progressbar01.setIndeterminate(false);

      progressbar02.setIndeterminate(false);

      button_bar.setOnClickListener(new Button.OnClickListener(){

      @Override

      public void onClick(View v) {

       // TODO Auto-generated method stub

       progressbar01.setVisibility(View.VISIBLE);//設為可見狀态

       progressbar02.setVisibility(View.VISIBLE);

       progressbar01.setMax(100);//設定最大值

       progressbar01.setProgress(0);//設定目前值

       progressbar02.setProgress(0);

       progressbar01.setSecondaryProgress(80);//設定第二進度值

       new Thread(new Runnable() {

        @Override

        public void run() {

         // TODO Auto-generated method stub

         for(int i=0;i<200;i++){      

          try{

           count = i*1;

           Thread.sleep(10);

          if(i==98){

           Message m = new Message();

           m.what = ProgressBar_Handler.STOP;

           ProgressBar_Handler.this.handler.sendMessage(m);       

          }else{

           Message m = new Message();-----------------------------------------------------------------更新進度條的方法

           m.what = ProgressBar_Handler.CURRENT;

           ProgressBar_Handler.this.handler.sendMessage(m);

          }

          }catch(Exception e){

           e.printStackTrace();      

          }

         }

        }

       }).start();

      }});

     }

     Handler handler = new Handler(){

      public void handleMessage(Message msg){

       switch(msg.what){

        case ProgressBar_Handler.STOP:

         progressbar01.setVisibility(View.GONE);

         progressbar02.setVisibility(View.GONE);

         //setVisible(false);

         Thread.currentThread().interrupt();

         break;

        case ProgressBar_Handler.CURRENT:

         if(!Thread.currentThread().isInterrupted()){

          progressbar01.setProgress(count);

          progressbar01.setSecondaryProgress(count+20);

          progressbar02.setProgress(count);

         setProgress(count*100);//設定标題欄中前面的一個進度條進度值

         setSecondaryProgress(count*100+30);//設定标題欄中後面的一個進度條進度值

         }

         break;

       }

       super.handleMessage(msg);

      }

     };

    }

   ========================================================================================================================================

   SeekBar 拖動條

    作用:如音量調節等。要實作監聽就需要實作SeekBar.OnSeekChangeListener接口。在SeekBar中需要監聽3個事件,他們是:

    在變化(onProgressChanged)在此可得到目前數值

    開始拖動(onStartTrackingTouch),

    停止拖動(onStopTrackingTouch)。

    seekBar.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     >

     <SeekBar 

      android:id= "@+id/seekBar"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:max="100"

      android:progress="50"

      android:secondaryProgress="75"

     />

     <TextView 

      android:id="@+id/textView1_SeekBar"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

     />

     <TextView

      android:id="@+id/textView2_SeekBar"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="共選"

     />

    </LinearLayout>

    public class SeekBar1 extends Activity implements OnSeekBarChangeListener{

     public SeekBar seekBar;

     public TextView textView1_SeekBar;

     public TextView textView2_SeekBar;

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.seekbar);

      seekBar = (SeekBar)findViewById(R.id.seekBar);

      textView1_SeekBar = (TextView)findViewById(R.id.textView1_SeekBar);

      textView2_SeekBar = (TextView)findViewById(R.id.textView2_SeekBar);

      seekBar.setOnSeekBarChangeListener(this);//為seekBar設定監聽器--------------------------------------------------------SeekBar監聽器

     }

     @Override

     public void onProgressChanged(SeekBar seekBar, int progress,//位置改變

        boolean fromUser) {

      // TODO Auto-generated method stub

      textView1_SeekBar.setText("目前值"+progress);

     }

     @Override

     public void onStartTrackingTouch(SeekBar seekBar) {//開始拖到

      // TODO Auto-generated method stub

      textView2_SeekBar.setText("正在調解");

     }

     @Override

     public void onStopTrackingTouch(SeekBar seekBar) {//停止拖動

      // TODO Auto-generated method stub

      textView2_SeekBar.setText("停止調解");

     }

    }

   =====================================================================================================================================================

   Notification和NoticationManager狀态欄提示

    當有未接電話,或電話時,在Android狀态欄中就會出現一個小圖示,如果下拉狀态欄就可以展開看到快訊通知。下面這個例子需要倆個Activity。

    notification1_manager.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

      android:orientation="vertical"

      android:layout_width="fill_parent"

      android:layout_height="fill_parent"

      >

      <TextView

       android:id="@+id/textView_Manager"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="我是怎麼出來的?我是Notification_Manager"

      />

    </LinearLayout>

    notification2_manager.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     >

     <Button

      android:id="@+id/button1_notification"

      android:layout_height="wrap_content"

      android:layout_width="wrap_content"

      android:text="通知_發出預設聲音"

     />

     <Button

      android:id="@+id/button2_notification"

      android:layout_height="wrap_content"

      android:layout_width="wrap_content"

      android:text="通知_發出震動"

     />

     <Button

      android:id="@+id/button3_notification"

      android:layout_height="wrap_content"

      android:layout_width="wrap_content"

      android:text="通知_螢幕發亮"

     />

     <Button

      android:id="@+id/button4_notification"

      android:layout_height="wrap_content"

      android:layout_width="wrap_content"

      android:text="通知_發出聲音,發亮,震動"

     />

    </LinearLayout>

    public class Notification_Manager extends Activity{

     public TextView textView_manager;

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.notification1_manager);

      textView_manager =(TextView)findViewById(R.id.textView_Manager);

      textView_manager.setOnClickListener(new TextView.OnClickListener(){

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        Intent intent = new Intent();

        intent.setClass(Notification_Manager.this, Notification2_Manager.class);

        startActivity(intent);

        Notification_Manager.this.finish();

       }

      });

     }

    }

    public class Notification2_Manager extends Activity{

     public Button button1_notification,

      button2_notification,

      button3_notification,

      button4_notification;

     NotificationManager notificationManager;//聲明通知消息管理器 Android系統提供NotificationManager來管理狀态欄消息,

      Intent intent;

      PendingIntent pendingIntent;

     Notification notification;  //Android系統提供Notification來處理這些快訊資訊,可以對Notification的内容,圖示,标題等進行設定

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.notification2_manager);

      //初始化notification對象

      notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);//通過getSystemService來獲得NotficationManger對象

      //構造Notification對象

      notification = new Notification();

      button1_notification =(Button)findViewById(R.id.button1_notification);

      button2_notification =(Button)findViewById(R.id.button2_notification);

      button3_notification =(Button)findViewById(R.id.button3_notification);

      button4_notification =(Button)findViewById(R.id.button4_notification);

      intent = new Intent(Notification2_Manager.this,Notification_Manager.class);//點選通知轉移内容

      //設定點選通知時顯示内容的類。Penging中文意思就是:待定,将來發生或來臨。

      //PendingIntent不是像Intent那樣立即發生,而是在合适的時候才會去觸發對應的 Intent

      pendingIntent = PendingIntent.getActivity(Notification2_Manager.this,0,intent, 0);

      button1_notification.setOnClickListener(new Button.OnClickListener(){

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        notification.icon =R.drawable.qq;//設定通知在狀态欄的圖示

        notification.tickerText ="我是QQ";//當我們點選通知時顯示的内容

        notification.defaults =notification.DEFAULT_SOUND;//通知發出預設的聲音

        //設定通知顯示的參數(這兩參數下拉可以看見)

        notification.setLatestEventInfo(Notification2_Manager.this,"發出預設的聲音","聲音",pendingIntent);

        notificationManager.notify(0,notification);//可以了解執行這個通知

       }});

      button2_notification.setOnClickListener(new Button.OnClickListener(){

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        notification.icon =R.drawable.qq;//設定通知在狀态欄的圖示

        notification.tickerText ="我是QQ";//當我們點選通知時顯示的内容

        notification.defaults =notification.DEFAULT_VIBRATE;//通知發出震動

        //設定通知顯示的參數(這兩參數下拉可以看見)

        notification.setLatestEventInfo(Notification2_Manager.this,"發出震動","震動",pendingIntent);

        notificationManager.notify(0,notification);//通過notify來執行Notification快訊,可以了解執行這個通知。

       }});

      button3_notification.setOnClickListener(new Button.OnClickListener(){

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        notification.icon =R.drawable.qq;//設定通知在狀态欄的圖示

        notification.tickerText ="我是QQ";//當我們點選通知時顯示的内容

        notification.defaults =notification.DEFAULT_LIGHTS;//通知時螢幕發亮

        //設定通知顯示的參數(這兩參數下拉可以看見)

        notification.setLatestEventInfo(Notification2_Manager.this,"螢幕發亮","發亮",pendingIntent);

        notificationManager.notify(0,notification);//可以了解執行這個通知

       }});

      button4_notification.setOnClickListener(new Button.OnClickListener(){

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        notification.icon =R.drawable.qq;//設定通知在狀态欄的圖示

        notification.tickerText ="我是QQ";//當我們點選通知時顯示的内容

        notification.defaults =notification.DEFAULT_ALL;//通知發出預設的聲音,發亮,震動

        //設定通知顯示的參數(這兩參數下拉可以看見)

        notification.setLatestEventInfo(Notification2_Manager.this,"聲音,發亮,震動","3者都有",pendingIntent);

        notificationManager.notify(0,notification);//可以了解執行這個通知

       }});

     }

    }

   ======================================================================================================================================

   ProgressDialog 對話框中的進度條的

    可以通過如下方法對PogressDialog進行設定

    setProgressDialog //設定進度條風格

    setTitle:        //設定标題

    setMessage       //設定提示資訊

    setIcon         //設定标題圖示

    setIndeterminate//設定進度條是否不明确

    setCancelable  //設定是否可以按退回按鍵取消

    setButton    //設定一個Button需要監聽Button事件

    show   //顯示進度條

    progressdialog.xml

    <?xml version="1.0"    encoding="utf-8"?>  

    <LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android" 

     android:orientation="horizontal"  

     android:layout_width="fill_parent"  

     android:layout_height="fill_parent"  

     android:padding="10dp"  

     >  

     <Button 

      android:id="@+id/button1_dialog"  

      android:layout_width="wrap_content"  

      android:layout_height="wrap_content"  

      android:text="長形進度條" 

     />  

     <Button 

      android:id="@+id/button2_dialog"  

      android:layout_width="wrap_content"  

      android:layout_height="wrap_content"  

      android:textColor="#FFF" 

      android:text="圓形進度條"

     />  

    </LinearLayout> 

    public class Progress_Dialog extends Activity{

     public Button button1_Dialog;

     public Button button2_Dialog;

     ProgressDialog progressDialog;//聲明進度條對話框

     private int count;

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.progressdialog);

      button1_Dialog = (Button)findViewById(R.id.button1_dialog);

      button2_Dialog = (Button)findViewById(R.id.button2_dialog);

      button1_Dialog.setOnClickListener(new Button.OnClickListener(){

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        //建立ProgressDialog對象

        progressDialog = new ProgressDialog(Progress_Dialog.this);

        //設定進度長形進度條風格

        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        //設定進度條标題

        progressDialog.setTitle("長形進度條");

        //設定提示資訊

        progressDialog.setMessage("如何改變其圖檔與形式");

        //設定标題圖示

        progressDialog.setIcon(R.drawable.qq);

        //設定進度條是否明确

        progressDialog.setIndeterminate(false);

        //設定是否可以按退出按鍵取消

        progressDialog.setCancelable(true);

        //設定進度條的一個Button按鈕

        progressDialog.setButton("确定", new DialogInterface.OnClickListener() {

         @Override

         public void onClick(DialogInterface dialog, int which) {

          // TODO Auto-generated method stub

          dialog.cancel();//點選确定按鈕取消對話框

         }

        });

        //顯示進度條

        progressDialog.show();

       }});

      button2_Dialog.setOnClickListener(new Button.OnClickListener(){ 

       @Override

       public void onClick(View v) {

        // TODO Auto-generated method stub

        //建立ProgressDialog對象

        progressDialog = new ProgressDialog(Progress_Dialog.this);

        //設定進度條風格

        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        //設定進度條标題

        progressDialog.setTitle("圓形進度條");

        //設定提示資訊

        progressDialog.setMessage("如何改變其圖檔與形式");

        //設定标題圖示

        progressDialog.setIcon(R.drawable.qq);

        //設定進度條是否明确

        progressDialog.setIndeterminate(false);

        //設定是否可以按退出按鍵取消

        progressDialog.setCancelable(true);

        //設定進度條的一個Button按鈕

        progressDialog.setButton("确定", new DialogInterface.OnClickListener() {

         @Override

         public void onClick(DialogInterface dialog, int which) {

          // TODO Auto-generated method stub

          dialog.cancel();//點選确定按鈕取消對話框

         }

        });

        //顯示進度條

        progressDialog.show();

         new Thread(){

          public void run(){

          try{

           while(count <=100){

            progressDialog.setProgress(count++);//由線程來控制進度值

            Thread.sleep(100);

           }

           progressDialog.cancel();

          }catch(InterruptedException e){

           progressDialog.cancel();

          }

          }

         }.start();

       }});

      }

    }

   ==================================================================================================================================================

 3.3  LayoutInflater

    layoutinflater.xml

    <?xml version="1.0"    encoding="utf-8"?>  

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

     android:orientation="vertical"  

     android:layout_width="fill_parent"  

     android:layout_height="fill_parent"  

     >  

     <TextView    

      android:layout_width="fill_parent"   

      android:layout_height="wrap_content"   

      android:text="@string/hello"  

     />  

     <Button  

      android:id="@+id/button"  

      android:layout_width="wrap_content"  

      android:layout_height="wrap_content"  

      android:text="ShowCustomDialog"  

     />  

    </LinearLayout> 

    layoutinflater2.xml

    <?xml version="1.0"    encoding="utf-8"?>  

    <LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android" 

     android:orientation="horizontal"  

     android:layout_width="fill_parent"  

     android:layout_height="fill_parent"  

     android:padding="10dp"  

     >  

     <ImageView android:id="@+id/image"  

      android:layout_width="wrap_content"  

      android:layout_height="fill_parent"  

      android:layout_marginRight="10dp"  

     />  

     <TextView android:id="@+id/text"  

      android:layout_width="wrap_content"  

      android:layout_height="fill_parent"  

      android:textColor="#FFF"  

     />  

     </LinearLayout> 

     public class LayoutInflaterDemo extends Activity implements OnClickListener { 

      private Button button;  

      public void onCreate(Bundle savedInstanceState) {  

       super.onCreate(savedInstanceState);  

       setContentView(R.layout.layoutinflater);  

       button = (Button)findViewById(R.id.button);  

       button.setOnClickListener(this); //添加監聽器 

      }  

      @Override  

      public void onClick(View v) {          

       showCustomDialog();  

      }       

      public void showCustomDialog(){  

       AlertDialog.Builder builder;  

       AlertDialog alertDialog;  

       Context mContext = LayoutInflaterDemo.this;   

       LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE); 

       View layout = inflater.inflate(R.layout.layoutinflater2,null);  

       TextView text = (TextView) layout.findViewById(R.id.text);  

       text.setText("Hello, 我的名字叫QQ!");  

       ImageView image = (ImageView) layout.findViewById(R.id.image);  

       image.setImageResource(R.drawable.qq);  

       builder = new AlertDialog.Builder(mContext);  

       builder.setView(layout);  

       alertDialog = builder.create();  

       alertDialog.show();  

      }  

     } 

   * LayoutInflater的使用,在實際開發種LayoutInflater這個類還是非常有用的,

   * 它的作用類似于 findViewById(),不同點是LayoutInflater是用來找layout下

   * xml布局檔案,并且執行個體化!而findViewById()是找具體xml下的具體 widget控

   * 件(如:Button,TextView等)。

   * 例如:

    public class LayoutInflaterActivity extends Activity {

     private EditText et;

     private Button btn;

     @Override

     public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      // 第一種方法

      LayoutInflater inflater = LayoutInflater.from(this);

      View layout = inflater.inflate(R.layout.main, null);

      // 第二種方法

      // LayoutInflater inflater = getLayoutInflater();

      // View layout = inflater.inflate(R.layout.main, null);

      // 第三種方法

      // LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

      // View layout = inflater.inflate(R.layout.main, null);

      // 這裡是通過事先獲得的布局檔案來執行個體化具體控件,并且可以根據情況自定義控件

      et = (EditText) layout.findViewById(R.id.edittext);

      et.setBackgroundColor(Color.YELLOW);

      btn = (Button) layout.findViewById(R.id.btn);

      btn.setBackgroundColor(Color.CYAN);

      // 顯示

      setContentView(layout);

     }

    }

   另外補充下,getSystemService是Activity中的方法,根據傳入的name來取得對應的服務對象,這些服務名稱參數都是Context類中的常量:

   傳入的Name 傳回的對象 說明

    WINDOW_SERVICE     WindowManager 管理打開的視窗程式

    LAYOUT_INFLATER_SERVICE  LayoutInflater 取得xml裡定義的view

    ACTIVITY_SERVICE    ActivityManager 管理應用程式的系統狀态

    POWER_SERVICE     PowerManger 電源的服務

    ALARM_SERVICE     AlarmManager 鬧鐘的服務

    NOTIFICATION_SERVICE   NotificationManager 狀态欄的服務

    KEYGUARD_SERVICE    KeyguardManager 鍵盤鎖的服務

    LOCATION_SERVICE    LocationManager 位置的服務,如GPS

    SEARCH_SERVICE     SearchManager 搜尋的服務

    VEBRATOR_SERVICE    Vebrator 手機震動的服務

    CONNECTIVITY_SERVICE   Connectivity 網絡連接配接的服務

    WIFI_SERVICE WifiManager  Wi-Fi服務

    TELEPHONY_SERVICE    TeleponyManager 電話服務

   ======================================================================================================================================

 3.4    界面布局

   LinearLayout 線性布局 但一行(列)隻能放一個控件

     android:orientation="vertical"//垂直線性布局

     android:orientation="horizontal"//水準線性布局

     android:layout_weight="1"//控件權重,即占螢幕的比例 預設為0

   RelativeLayout 相對布局

    其參數有:Width,Height,Below,AlignTop,Toleft,Padding,MarginLeft注意其值都是相對其他元素來說的。

    android:layout_toLeftOf="@id/ok"

    android:layout_alignTop="@id/ok"

    android:layout_below="@id/ok"

    android:layout_marginLeft="10dip"

    android:layout_alignParentRight="true"

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

     <TextView

      android:id="@+id/label"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="請輸入:"/>

     <View----------------------------------------------------------------------------View在xml檔案中的運用

      android:layout_height="2dip"

      android:background="#FF909090" />

    </RelativeLayout>

   TableLayout 表單布局

    TableLayout容器不會顯示Row,Column,Cell的邊框線。

    <?xml version="1.0" encoding="utf-8"?>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

     android:orientation="vertical"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent"

     >

     <TableRow>

      <TextView 

       android:id= "@+id/textView1"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:text="Button,TextView,EditView"

      />

      <TextView 

       android:id ="@+id/textView2"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:text="SimpleAdapter"

       android:gravity="right"

      />

     </TableRow>

    </TableLayout>

   FrameLayout 裡面隻可以有一個控件,且此不能設定此控件位置,此控件總是位于左上角

   AbsoluteLayout 裡面可以放多個控件,可以定義自己控件的x,y

   TabWidget 切換卡 通過繼承TabActivity來實作。TabHost 是一個用來存放多個Tab标簽的容器,要使用TabHost,要通過getTabHost方法來獲得TabHost對象,然後通過addTab方法來向

    TabHost中添加Tab.

    main.xml

    <?xml version="1.0" encoding="utf-8"?>

    <TabHost xmlns:android="http://schemas.android.com/apk/res/android"

     android:id="@android:id/tabhost"

     android:layout_width="fill_parent"

     android:layout_height="fill_parent">

     <LinearLayout

      android:orientation="vertical"

      android:layout_width="fill_parent"

      android:layout_height="fill_parent">

      <TabWidget

       android:id="@android:id/tabs"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content" />

      <FrameLayout

       android:id="@android:id/tabcontent"

       android:layout_width="fill_parent"

       android:layout_height="fill_parent">

       <TextView

        android:id="@+id/textview1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:text="this is a tab" />

       <TextView

        android:id="@+id/textview2"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:text="this is another tab" />

       <TextView

        android:id="@+id/textview3"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:text="this is a third tab" />

      </FrameLayout>

     </LinearLayout>

    </TabHost>

    public class Activity01 extends TabActivity{

      //聲明TabHost對象

     TabHost mTabHost;

     @Override

     public void onCreate(Bundle savedInstanceState){

      super.onCreate(savedInstanceState);

      setContentView(R.layout.main); 

      //取得TabHost對象

      mTabHost = getTabHost();

      mTabHost.addTab(mTabHost.newTabSpec("tab_test1")//建立一個newTabSpec(newTabSpec)

       .setIndicator("TAB 1",getResources().getDrawable(R.drawable.img1)) //設定其标簽和圖示(setIndicator)

       .setContent(R.id.textview1));//設定内容(setContent)

      mTabHost.addTab(mTabHost.newTabSpec("tab_test2")

       .setIndicator("TAB 2",getResources().getDrawable(R.drawable.img2))

       .setContent(R.id.textview2));

      mTabHost.addTab(mTabHost.newTabSpec("tab_test3")

       .setIndicator("TAB 3",getResources().getDrawable(R.drawable.img3))

       .setContent(R.id.textview3));

      mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));//設定TabHost的背景顔色  

      //mTabHost.setBackgroundResource(R.drawable.bg0);//設定TabHost的背景圖檔資源

      mTabHost.setCurrentTab(0); //設定目前顯示哪一個标簽

      mTabHost.setOnTabChangedListener(new OnTabChangeListener(){ //标簽切換事件處理,setOnTabChangedListener -------------------------------------------TabWidget監聽器

       @Override

       public void onTabChanged(String tabId){

        Dialog dialog = new AlertDialog.Builder(Activity01.this)

         .setTitle("提示")

         .setMessage("目前選中:"+tabId+"标簽")

         .setPositiveButton("确定",

          new DialogInterface.OnClickListener(){

           public void onClick(DialogInterface dialog, int whichButton){

            dialog.cancel();

           }

          }).create();//建立按鈕       

          dialog.show();

       }           

      });

     }

    }