上下文菜單(ContextMenu)是 Android 中常見的互動形式,當使用者長按某個檢視時便會彈出,非常適合用來提供「分享」、「刪除」等針對特定項目的操作。以下透過一個完整範例,示範如何為 TextView 註冊並實作上下文菜單。
主程式碼
- package com.cloay;
-
- import Android.app.Activity;
- import android.os.Bundle;
- import android.view.ContextMenu;
- import android.view.ContextMenu.ContextMenuInfo;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.TextView;
- import android.widget.Toast;
- /**
- *
- * MyContextMenuActivity.java
- * @author cloay
- * 2011-10-18
- */
- public class MyContextMenuActivity extends Activity {
- private TextView textView = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView = (TextView) findViewById(R.id.text);
- registerForContextMenu(textView); //為視圖註冊上下文菜單
- }
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v,
- ContextMenuInfo menuInfo) {
- menu.setHeaderIcon(android.R.drawable.ic_menu_share);
- menu.setHeaderTitle("Share to friends");
- menu.add(Menu.NONE, 0, 0, "發送");
- menu.add(Menu.NONE, 1, 1, "分享");
- super.onCreateContextMenu(menu, v, menuInfo);
- }
- @Override
- public boolean onContextItemSelected(MenuItem item) {
- switch(item.getItemId()){
- case 0:
- Toast.makeText(this, "發送給手機聯繫人!", Toast.LENGTH_SHORT).show();
- break;
- case 1:
- Toast.makeText(this, "分享到微博!", Toast.LENGTH_SHORT).show();
- break;
- }
- return super.onContextItemSelected(item);
- }
-
- }
程式的關鍵在於三步:先用 registerForContextMenu() 為目標檢視註冊,再重寫 onCreateContextMenu() 定義菜單的標題、圖示與選項,最後透過 onContextItemSelected() 處理使用者點選後的反應。
版面配置
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:paddingTop="10dip"
- >
- <TextView android:id="@+id/text"
- android:paddingTop="10dip"
- android:textColor="#FFA07A"
- android:background="@drawable/bg_normal"
- android:text="@string/hello"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- </LinearLayout>
完成上述步驟後,長按畫面上的文字,即可看到帶有標題與圖示的上下文菜單彈出,點選不同選項會觸發對應的 Toast 提示。