Override onOptionsItemSelected(MenuItem item)
. Vì vậy, nó sẽ như thế nào
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
// do whatever
return true;
default:
return super.onOptionsItemSelected(item);
}
}
EDIT:
Vì đây đã nhận được rất nhiều điểm, tôi nên lưu ý rằng nó là rất tốt để thêm ID vào tùy chọn menu. Một cách tốt để đảm bảo chúng luôn là duy nhất là xác định chúng trong tài nguyên ids.xml
được đặt trong thư mục res/values
.
ids.xml
<resources>
<item name="menu_action1" type="id"/>
<item name="menu_action2" type="id"/>
<item name="menu_action3" type="id"/>
</resources>
Sau đó, khi bạn ghi đè lên các phương pháp onCreateOptionsMenu(Menu menu)
, bạn có thể sử dụng các ID như vậy:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, R.id.menu_action1, Menu.NONE, R.string.menu_action1);
menu.add(Menu.NONE, R.id.menu_action2, Menu.NONE, R.string.menu_action1);
return true;
}
Override onOptionsItemSelected(MenuItem item)
.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_action1:
// do whatever
return true;
case R.id.menu_action2:
// do whatever
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Lý do bạn làm điều này là Activity
sẽ ghi đè này với các tùy chọn trình đơn, nhưng Fragments
cũng có thể thêm các mục menu riêng của họ. Sử dụng ids.xml
đảm bảo các ID là duy nhất cho dù chúng được đặt theo thứ tự nào.
Là một thực hành lập trình tốt, tôi sẽ sử dụng id thay vì mã hóa cứng các số trong trường hợp. –