res/menu(名稱不可更改) 新建(new)Directory 名稱:menu_main.xml
<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/about" //對應到MainActivity中用以取值,用id判斷按了哪個按鈕(呼叫哪個方法)
android:title="@string/menu_about" //對應到string.xml
android:icon="@drawable/help_browser"
android:orderInCategory="1" //代表這個東西在扛棒上的位置,越小越左(上?),同數字的話已寫在上面的優先
app:showAsAction="always"/> //是否一開式窗及產生這個東西在扛棒上
<item android:id="@+id/exit"
android:title="@string/menu_exit"
android:icon="@drawable/emblem_unreadable"
android:orderInCategory="2"
app:showAsAction="always"/>
</menu>
package com.lcpan.i18n;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about: showAboutDialog(); break;
case R.id.exit: finish(); break;
// android.app.Activity是AppCompatActivity爺爺,finish ()定義在爺爺中
// void finish ()
// Call this when your activity is done and should be closed.
// The ActivityResult is propagated back to whoever launched you via onActivityResult().
}
return super.onOptionsItemSelected(item);
}
private void showAboutDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.about_title);
builder.setMessage(R.string.about_msg);
builder.setPositiveButton(R.string.confirm,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
}
);
builder.show();
}
}
全站熱搜
留言列表