2. 需覆寫onCreateContextMenu及onContextItemSelected這二個方法
3. MainActivity.java
import android.app.Activity; import android.app.Activity; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); LinearLayout windowLayout = (LinearLayout) findViewById(R.id.windowLayout); //註冊長按選單 this.registerForContextMenu(windowLayout); } @Override public boolean onContextItemSelected(MenuItem item) { //當使用者點選項目時,所需的動作 Toast.makeText(this, "您選擇的是"+item.getTitle(), Toast.LENGTH_SHORT).show(); return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo menuInfo) { //設定選單內容 super.onCreateContextMenu(contextMenu, view, menuInfo); contextMenu.add(0, 0, 0, "紅茶"); contextMenu.add(0, 1, 0, "奶茶"); contextMenu.add(0, 2, 0, "綠茶"); contextMenu.add(0, 3, 0, "青茶"); } }
3. main.xml(Layout)
<?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/windowLayout"> </LinearLayout>
4. 執行之後的畫面。