Tôi có những mục trình đơn trong tôi menu_main.xml
Làm thế nào để lập trình kích hoạt/bấm vào một MenuItem trong Android?
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="@+id/action_restart" android:title="Restart"
android:orderInCategory="1" />
<item android:id="@+id/action_clear" android:title="Clear"
android:orderInCategory="2" />
<item android:id="@+id/action_update" android:title="Update"
android:orderInCategory="3" />
<item android:id="@+id/action_about" android:title="About"
android:orderInCategory="4" />
<item android:id="@+id/action_try_restart" android:title="Try Restart"
android:orderInCategory="5" />
</menu>
Và tôi có điều này trong onOptionsItemSelected
phương pháp của tôi:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_restart) {
Toast.makeText(MainActivity.this, "Restart...", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_clear) {
Toast.makeText(MainActivity.this, "Clear...", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_update) {
Toast.makeText(MainActivity.this, "Update...", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_about) {
Toast.makeText(MainActivity.this, "About...", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_try_restart) {
// how to click/trigger the "action_restart" from here?
}
return super.onOptionsItemSelected(item);
}
Tôi đã thử với:
MenuItem actionRestart = (MenuItem) findViewById(R.id.action_restart);
actionRestart; //
Nhưng actionRestart
tham khảo doesn' t cung cấp mọi thứ như click
, trigger
, v.v.
Tôi cũng muốn lưu ý rằng tôi mới phát triển Android và tôi đến từ nền PHP/JavaScript, vì vậy mức độ OOP Java này hoàn toàn mới đối với tôi.
Thanks buddy/Hvala Zemljače! Tôi đã thực hiện một phương pháp riêng biệt mà tôi gọi nó trên cả hai; 'action_restart' và' action_try_restart', để phù hợp với nhu cầu của tôi bây giờ. Chúc mừng! – omerowitz
bạn có thể sử dụng phương thức performIdentifierAction – Simon