上下文菜單項不支持圖標或快捷鍵.
要創建一個上下文菜單, 必須重寫Activity的上下文菜單回調方法: onCreateContextMenu() 和 onContextItemSelected(). 在onCreateContextMenu()回調方法中, 可以使用add()方法添加單項, 或擴展一個XML定義的菜單資源(menu resource). 然後使用registerForContextMenu()將ContextMenu註冊到視圖上.
在這個例子中, 我們將註冊一個上下文菜單在整個屏幕上, 因此, 首先修改main.xml為整個LinearLayout添加一個id.
<?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"
android:id="@+id/wholeview"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
然後修改主程序重寫onCreateContextMenu() 和 onContextItemSelected(), 並在onCreate()方法中把上下文菜單註冊到LinearLayout上.
package com.AndroidContextMenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class AndroidContextMenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout wholeWiew = (LinearLayout)findViewById(R.id.wholeview);
registerForContextMenu(wholeWiew);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case 0:
Toast.makeText(this, "Option 0", Toast.LENGTH_LONG).show();
return true;
case 1:
Toast.makeText(this, "Option 1", Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(this, "Option 2", Toast.LENGTH_LONG).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 0, 0, "Option 0");
menu.add(0, 1, 0, "Option 1");
menu.add(0, 2, 0, "Option 2");
}
}
沒有留言:
發佈留言