main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="请点击菜单键" /> </RelativeLayout>
dialog.xml如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="20sp" android:textColor="@android:color/white" android:text="this is a dialog" /> </RelativeLayout>
main.xml如下:
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/exit" android:icon="@drawable/ic_launcher" android:title="退出"/> <item android:id="@+id/aboutme" android:title="About me"/> </menu>
MainActivity如下:
package com.wy; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = this.getMenuInflater(); menuInflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.exit) { finish(); } if(item.getItemId() == R.id.aboutme) { AlertDialog.Builder builder = new Builder(this); LayoutInflater inflater=getLayoutInflater(); View xmlView=inflater.inflate(R.layout.dialog, null); builder.setView(xmlView); AlertDialog dialog=builder.create(); dialog.setIcon(R.drawable.ic_launcher); dialog.setTitle("welcome"); dialog.setButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface clickedDialog, int arg1) { clickedDialog.cancel(); } }); dialog.show(); } return super.onOptionsItemSelected(item); } }