LayoutInflater是用来找layout下xml布局文件,并且实例化!
findViewById()是找具体xml下的具体 widget控件.
什么时候需要用到 LayoutInflater?
在使用SlidingDrawer的时候,可能会用到,但是鉴于情况比较复杂,现在用一个AlertDialog来进行演示
当点击一个Button之后,会弹出AlertDialog来,在这个AlertDialog里,使用了自定义的custom.xml布局,
在custom.xml有一个ImageView ,Button以及TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/imgView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/textView"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/custom_btn"
android:text="Click Me"
/>
</LinearLayout>
.java代码
private void showCusomDialog()
{
AlertDialog.Builder builder;
final AlertDialog dlg;
Context context = this;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom,null);
TextView textView = (TextView)layout.findViewById(R.id.textView);
textView.setText("Hello Fuck ");
ImageView imgView = (ImageView)layout.findViewById(R.id.imgView);
imgView.setImageResource(R.drawable.icon);
builder = new AlertDialog.Builder(context);
builder.setView(layout);
dlg = builder.create();
dlg.show();
Button btn = (Button)layout.findViewById(R.id.custom_btn);
btn.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v )
{
Toast.makeText(MainActivity.this, "Fuck YOU",Toast.LENGTH_SHORT).show();
dlg.dismiss();
}
});
/* 原来的显示方式
new AlertDialog.Builder(this)
.setMessage("what")
.setTitle("Title")
.setPositiveButton("", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
www.aidsex.cn
}
}
)
.create()
.show();
*/
}