Context Menu
Đây là dạng menu hiển thị lựa chọn khi người dùng thao tác với 1 đối tượng trong nhóm đối tượng có cùng tính chất. Ví dụ như khi thao tác chọn với 1 danh sách sinh viên, ta có thể đưa ra context menu với các tùy chọn như: thêm, sửa, xóa, hiển thị chi tiết. Để sử dụng context menu, người dùng cần đăng ký đối tượng cho context menu. Để gọi, người dùng cần bấm giữ đối tượng trong vài giây.Các bước để tạo Context Menu
Bước 1: Khai báo menu (tạo mới 1 file menu_phone.xml trong thư mục menu) và viết mã code như bên dưới.
Bước 2: Trong hàm onCreateContextMenu thì đăng ký hiển thị menu xml vừa tạo ở trên.
getMenuInflater().inflate(R.menu.menu_phone, menu);
Bước 3: Trong hàm onContextItemSelected đăng ký xử lý sự kiện khi click lựa chọn trên menu
@Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item .getMenuInfo(); String name = mContact[info.position]; switch (item.getItemId()) { case R.id.menu_call: Toast.makeText(ContextMenu2Activity.this, "Call to " + name, Toast.LENGTH_SHORT).show(); break; case R.id.menu_sms: Toast.makeText(ContextMenu2Activity.this, "SMS to " + name, Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(ContextMenu2Activity.this, "Do some thing with " + name, Toast.LENGTH_SHORT).show(); break; } return super.onContextItemSelected(item); }
Bước 4: Đăng ký Context Menu cho một đối tượng trên layout của Activity.
registerForContextMenu(listContact);
Option Menu - Actionbar
Đối với các phiên bản Android 2.3 trở về trước, Option Menu trông có dạng như sau:Từ phiên bản Android > 2.3 thì Option Menu được hiểu như Actionbar và trông có dạng như sau:
Để tạo option menu - actionbar ta làm theo các bước như sau:
Bước 1: Khai báo file menu menu_main.xml trong thư mục menu với nội dung như sau:
Bước 2: Trong hàm onCreateOptionsMenu đăng ký sử dụng menu đã viết ở trên.
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); menu.add(1, 999, 999, "Menu 999").setIcon(R.drawable.more); return true; }Bước 3: Trong hàm onOptionsItemSelected đăng ký xử lý sự kiện khi click và item của menu.
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_1: Intent intent_1 = new Intent(MainActivity.this, ContextMenu1Activity.class); startActivity(intent_1); return true; case R.id.menu_2: Intent intent_2 = new Intent(MainActivity.this, ContextMenu2Activity.class); startActivity(intent_2); return true; case R.id.menu_3: return true; case R.id.menu_4: return true; case R.id.menu_5: return true; default: return super.onOptionsItemSelected(item); } }
Source code ví dụ có thể tải tại đây.
No comments:
Post a Comment