效果:
java代码
package com.example.dialogdemo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnShow = (Button) findViewById(R.id.btn_show);
btnShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 载入xml文件的布局
LayoutInflater lf = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup vg = (ViewGroup) lf.inflate(R.layout.layout_view,
null);
final EditText etShow = (EditText) vg
.findViewById(R.id.et_show);
new AlertDialog.Builder(MainActivity.this)
.setView(vg)
.setTitle("标题")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
String str = etShow.getText()
.toString();
System.out.println("str--->" + str);
}
}).setNeutralButton("忽略", null)
.setNegativeButton("取消", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
需要加载的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" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
<TableRow>
<TextView
android:layout_margin="5dp"
android:text="姓名" />
<EditText
android:id="@+id/et_show"
android:layout_width="100dp"
android:layout_margin="5dp"
android:inputType="text" />
</TableRow>
</TableLayout>
</RelativeLayout>