效果图
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MyLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/mybut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户登录" />
</LinearLayout>
login.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MyLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:text="用户名:"
android:textSize="16px" />
<EditText
android:layout_height="wrap_content"
android:width="60pt" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:text="密码:"
android:textSize="16px" />
<EditText
android:layout_height="wrap_content"
android:inputType="textPassword"
android:width="60pt" >
<requestFocus />
</EditText>
</TableRow>
</TableLayout>
package com.example.layoutinflater;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button mybut=null;//定义按钮组件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mybut=(Button)super.findViewById(R.id.mybut);
this.mybut.setOnClickListener(new OnClickListenerImpl());
}
public class OnClickListenerImpl implements OnClickListener{
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
LayoutInflater factory=LayoutInflater.from(MainActivity.this);
View myview=factory.inflate(R.layout.login,null);//将布局文件转变为View
Dialog dialog=new AlertDialog.Builder(MainActivity.this)//创建dialog
.setTitle("用户登录")
.setView(myview)
.setPositiveButton("登陆",//设置确定按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO 自动生成的方法存根
}
}).setNegativeButton("取消",//设置取消按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO 自动生成的方法存根
}
}).create();
dialog.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;
}
}