2013年1月8日 星期二

建立選單(Menu)

  1.  利用覆寫onCreateOptionsMenu, onOptionsItemSelected這二個方法來建立選單。
  2. Main.java
package com.rex.menu;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class Main extends Activity {
   private TextView describe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        describe=(TextView)findViewById(R.id.describe);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //參數1:群組id, 參數2:itemId, 參數3:item順序, 參數4:item名稱
        menu.add(0,0,0,"開始");
        menu.add(0,1,1,"結束");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //依據itemId來判斷使用者點選哪一個item
        switch(item.getItemId()){
             case 0:
                   describe.setText("開始了喔!...............");
                break;
             case 1:
                    finish();
                 break;
           
          default:
        }
        
        
        
        return super.onOptionsItemSelected(item);
    }
     
    

}

3. main.xml(Layout)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main" >

    <TextView
        android:id="@+id/describe"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="" />

</RelativeLayout>

4. 按下MENU鍵之後出現及點選「說明」之後出現的畫面




沒有留言:

張貼留言