在实际开发种LayoutInflater这个类还是非常有用的,它的作用类似于findViewById(),不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体widget控件(如:Button,TextView等)。
  主布局main.xml里有一个TextView和一个Button,当点击Button,出现Dialog,而这个Dialog的布局方式是我们在layout目录下定义的custom_dialog.xml文件(里面左右分布,左边ImageView,右边TextView)。
XML代码:
  <?xmlversion="1.0"encoding="utf-8"?>
  <LinearLayoutxmlns:andro/>
  
  </LinearLayout>
定义对话框的布局方式,我们在layout目录下,新建一个名为custom_dialog.xml文件具体代码如下:
XML代码:

  <?xmlversion="1.0"encoding="utf-8"?>
  <LinearLayoutxmlns:andro/>
  
  </LinearLayout>

  主程序LayouInflaterDemo.java代码如下:
  
    packageEOE.android.Demo;
  importandroid.app.Activity;
  importandroid.app.AlertDialog;
  importandroid.content.Context;
  importandroid.os.Bundle;
  importandroid.view.LayoutInflater;
  importandroid.view.View;
  importandroid.view.View.OnClickListener;
  importandroid.widget.Button;
  importandroid.widget.ImageView;
  importandroid.widget.TextView;
  
  publicclassLayoutInflaterDemoextendsActivityimplementsOnClickListener{
  privateButtonbutton;
  
  publicvoidonCreate(BundlesavedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  button=(Button)findViewById(R.id.button);
  button.setOnClickListener(this);
  }
  
  @Override
  publicvoidonClick(Viewv){
  showCustomDialog();
  }
  publicvoidshowCustomDialog(){
  AlertDialog.Builderbuilder;
  AlertDialogalertDialog;
  ContextmContext=LayoutInflaterDemo.this;
  
  //下面俩种方法都可以
  ////LayoutInflaterinflater=getLayoutInflater();
  
  LayoutInflaterinflater=(LayoutInflater)mContext.getSystemServic(LAYOUT_INFLATER_SERVICE);
  
  Viewlayout=inflater.inflate(R.layout.custom_dialog,null);
  TextViewtext=(TextView)layout.findViewById(R.id.text);
  text.setText("Hello,WelcometoMrWei'sblog!");
  ImageViewimage=(ImageView)layout.findViewById(R.id.image);
  image.setImageResource(R.drawable.icon);
  builder=newAlertDialog.Builder(mContext);
  builder.setView(layout);
  alertDialog=builder.create();
  alertDialog.show();
  }
  
  }  

 

相关文章:

  • 2021-10-10
  • 2021-07-16
  • 2021-10-01
  • 2022-12-23
  • 2022-01-02
  • 2022-02-14
猜你喜欢
  • 2021-06-30
  • 2022-12-23
相关资源
相似解决方案