不過平版或手機沒有滑鼠,所以則需要用長按的方法叫出選單。
MainActivity.java
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.Toast; public class MainActivity extends Activity { protected static final int MENU_BUTTON_1 = Menu.FIRST; protected static final int MENU_BUTTON_2 = Menu.FIRST + 1; protected static final int MENU_BUTTON_3 = Menu.FIRST + 2; protected static final int MENU_BUTTON_4 = Menu.FIRST + 3; /* Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //註冊長按選單 registerForContextMenu(findViewById(R.id.relativelayout)); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { //設定選單內容 menu.setHeaderTitle("挑選您要的顏色"); menu.add(0, MENU_BUTTON_1, 0, "紅"); menu.add(0, MENU_BUTTON_2, 0, "橙"); menu.add(0, MENU_BUTTON_3, 0, "黃"); menu.add(0, MENU_BUTTON_4, 0, "綠"); super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { // 點選項目後,要做的事寫在這邊 switch(item.getItemId()) { case MENU_BUTTON_1: Toast.makeText(getApplicationContext(), "您選了紅色", Toast.LENGTH_SHORT).show(); break; case MENU_BUTTON_2: Toast.makeText(getApplicationContext(), "您選了橙色", Toast.LENGTH_SHORT).show(); break; case MENU_BUTTON_3: Toast.makeText(getApplicationContext(), "您選了黃色", Toast.LENGTH_SHORT).show(); break; case MENU_BUTTON_4: Toast.makeText(getApplicationContext(), "您選了綠色", Toast.LENGTH_SHORT).show(); break; default: break; } return super.onContextItemSelected(item); } }
我們希望在畫面任何一個地方按下去,都會出現長按選單,
所以要在這裡加入ID。如:android:id="@+id/relativelayout"
activity_main.xml
<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" android:id="@+id/relativelayout" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="152dp" android:text="請長按螢幕" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
結果:
沒有留言:
張貼留言