Context Menu là một loại menu popup xổ ra khi người dùng longClick (Bấm và giữ lâu một lúc) vào một phần tử nào đó trên giao diện.
Bạn hãy tạo một ứng dụng mới để thực hành
Bước 1: Tạo layout cho menu
- Kích phải chuột lên thư mục res/ rồi chọn new --> chọn Android Resource Directory
- Thực hiện chọn Resource Type là menu ==> bấm OK
- Tiếp theo bạn kích phải chuột lên thư mục menu vừa tạo --> chọn new --> chọn Menu resource file
- Tiếp theo nhập tên cho menu là: context_menu_01 và bấm OK
- Nội dung file context_menu_01 như sau:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Item 1" android:id="@+id/item_1"/>
<item android:title="Item 2" android:id="@+id/item_2"/>
</menu>
Bước 2: Tạo 1 cái TextView để làm ví dụ context menu
- Trong file layout của activity bạn thêm một cái TextView như sau:
<TextView
android:id="@+id/tv_hello"
android:textSize="30dp"
android:text="Hello, long click me!"
android:padding="20dp"
android:background="#FFC107"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Bước 3: Trong hàm onCreate của activity khai báo một biến để tham chiếu tới TextView này
viết ở bên dưới lệnh setContentView nhé.
TextView textView = findViewById(R.id.tv_hello);
Bước 4: Đăng ký ContextMenu cho TextView
Bạn viết ở bên dưới dòng lệnh của bước 3 nhé.
registerForContextMenu(textView);
Bước 5: Bạn viết Overwrite cho 2 hàm khởi tạo và sự kiện chọn phần tử menu như sau:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater(); // sử dụng MenuInflater để điều khiển gắn view cho menu
inflater.inflate(R.menu.context_menu_01, menu);
menu.setHeaderTitle("Tiêu đề menu"); // thiết lập tiêu đề cho menu hiển thị, nếu không muốn thì bạn bỏ lệnh này.
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
// Bạn chọn menu nào thì thông báo ra menu đó
if(item.getItemId()==R.id.item_1){ // cái này là ID ở file res/menu/context_menu_01.xml
// Ví dụ sau này bạn làm chức năng: sửa, xóa dòng trên listView thì viết code ở đây.
Toast.makeText(getApplicationContext(),"Bạn chọn ITem 1",Toast.LENGTH_LONG).show();
}
else if(item.getItemId()==R.id.item_2){
Toast.makeText(getApplicationContext(),"Bạn chọn Item 2",Toast.LENGTH_LONG).show();
}else{
return false;
}
return true;
}
Bước 6: Bạn chạy thử ứng dụng
Bấm và giữ một lúc vào cái TextView hello sẽ nhìn thấy menu xổ ra
Bạn có thể sử dụng ContextMenu này ở ListView bằng cách thay TextView bằng ListView.