天天看点

Android中inflate简介

                           Android中inflate简介

      inflate的作用是把xml文件找出来,然后再使用找出来的xml文件中的控件。

      使用场景: 

      我们都知道,一个activity一般会绑定一个布局,然后我们使用findViewById()来寻找绑定的布局里的控件,

       当我们需要使用另一个layout布局中的控件的时候就需要使用inflate了

      例如: View view=View.inflate(this,R.layout.dialog_layout,null);

     TextViewdialogTV=(TextView)view.findViewById(R.id.dialog_tv);

     dialogTV.setText("abcd");

  如果直接用this.findViewById(R.id.dialog_tv)肯定会报错

  当然也可以使用LayoutInflater

       有三种方式:

       LayoutInflaterinflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      View layout =inflater.inflate(R.layout.main, null);

      LayoutInflater inflater =LayoutInflater.from(context);

   【Attention】

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference

为什么程序中会报这个错误,他说你找的是一个空对象,原因一半如下:

1、你没有findViewById(xxx)就是你没有找到控件却使用了,这个时候会告诉你对象为空。

2、你找了,但你找的是其他xml中的对象,本布局中无法使用。