施用LayoutInflater做简单的android聊天对话框
使用LayoutInflater做简单的android聊天对话框
2.使用LayoutInflater把布局文件转化为view
很简单吧,看下效果图吧
对话框我就不多说了,android其实是有很多内置的对话框的像日期、时间对话框,还有类似多选或单选下拉的。但是有的时候界面很复杂的时候,使用内置的这种方式可能会比较麻烦。android也给我们提供了一种分离的方式那就是使用LayoutInflater这个类来进行复杂的布局。一起来看一下吧。
1.编写界面的xml文件,我这里就使用表格布局
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow> <TextView android:text="用户名" android:layout_marginLeft="20dip" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <EditText android:width="60pt" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:text="密码" android:layout_marginLeft="20dip" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <EditText android:password="true" android:width="60pt" android:layout_height="wrap_content" /> </TableRow> </TableLayout>
2.使用LayoutInflater把布局文件转化为view
package org.lxh.mydialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; public class MyDailogActivity extends Activity { /** Called when the activity is first created. */ private Button but=null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); but=(Button)this.findViewById(R.id.button); but.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //将布局文件转化为view LayoutInflater flat=LayoutInflater.from(MyDailogActivity.this); View view=flat.inflate(R.layout.login, null); Dialog dialog=new AlertDialog.Builder(MyDailogActivity.this) .setIcon(android.R.drawable.star_on) .setTitle("用户登录") //不要忘记下面这句 .setView(view) .setPositiveButton("登录", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).create(); dialog.show(); } }); } }
很简单吧,看下效果图吧