幫Button加入"長按"選單
首先這是MainActivity的layout,XML的部份,只有一個Button
<?xml version="1.0" encoding="utf-8"?> <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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.boywhychen.context_menu.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/menu_btn" android:text="Context Menu" /> </RelativeLayout>
接下來我們需要在menu資料來下建立一個my_menu.xml
內容就是列出Menu中要顯示的Item內容以及順序
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/color_blue" android:title="Blue" android:orderInCategory="1" app:showAsAction="ifRoom"/> <item android:id="@+id/color_red" android:title="Red" android:orderInCategory="2" app:showAsAction="ifRoom"/> <item android:id="@+id/color_green" android:title="Green" android:orderInCategory="3" app:showAsAction="ifRoom"/> </menu>
接下來是主程式
package com.example.boywhychen.context_menu; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化Button Button menu_btn=(Button)findViewById(R.id.menu_btn); //幫Button註冊ContextMenu registerForContextMenu(menu_btn); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); //要使用的Context Menu XML檔案 getMenuInflater().inflate(R.menu.my_menu,menu); } @Override public boolean onContextItemSelected(MenuItem item) { //按下Context Menu Item要做的事 switch ((item.getItemId())) { case R.id.color_blue: Toast.makeText(MainActivity.this,"Blue",Toast.LENGTH_SHORT).show(); break; case R.id.color_green: Toast.makeText(MainActivity.this,"Green",Toast.LENGTH_SHORT).show(); break; case R.id.color_red: Toast.makeText(MainActivity.this,"Red",Toast.LENGTH_SHORT).show(); break; } return super.onContextItemSelected(item); } }
執行效果(記住是長按才會跳出選單~我一開始都用click都沒反應~搞了半天)
點下Red後,Toast會顯示你按下的是Red
參考來源:
The Complete Android Material Design Course: Become a Pro
https://www.udemy.com/android-material-design-course-tutorial/learn/v4/overview
上課心得筆記一下
沒有留言:
張貼留言