有关inflater.inflate函数的总结笔记

本文大部分都是我找的资料,因此也算不得原创,但因为转载和归纳的比较细致,所以我美其名曰原创。

inflate(layout-id,父视图,是否添加到父视图上)

首先我在子类化Fragment的时候有个函数like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,

                Bundle savedInstanceState) 
{

View view = inflater.inflate(R.layout.right_fragment, container, false);

            return view;
}
其二在写listview数据的时候,即adapter的时候有个方法用到:

     
     

@Override public View getView(int position, View convertView, ViewGroup parent) 

{

            News news = getItem(position);
            View view;
            if (convertView == null) 
	    {

view = LayoutInflater.from(getContext()).inflate(resourceId, null);

}

else 

{

                view = convertView;
            }

TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);newsTitleText.setText(news.getTitle());
return view;

通过上面两个地方我发现他们为何如此不同,所以反复查找资料,最后发现一个知识点详解如下:

LayoutInflater作用是将layoutxml布局文件实例化为View类对象。

获取LayoutInflater的方法有如下三种:

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

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

 

LayoutInflater inflater = LayoutInflater.from(context); (该方法实质就是第一种方法,可参考源代码)

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

 

LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数)

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

一直有点纠结setContentViewinflate的区别找了一些资料。写了个小程序看了下:

public class MyInflate extends Activity{

    private TextView tv;

    public void OnCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        //setContentView(R.layout.main);

        //tv = (TextView) findViewById(R.id.tv);

 

        LayoutInflater inflate = LayoutInflater.from(this);

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

        setContentView(view);

    }

}

上述注释掉的代码和没有注释掉的代码两种情况是相同的。

区别: setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这就需要LayoutInflater动态加载。

public View inflate(int Resourece,ViewGroup root) 作用:填充一个新的视图层次结构从指定的XML资源文件中 reSourceViewlayoutID root 生成的层次结构的根视图 return 填充的层次结构的根视图。如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。

其余几个重载的inflate函数类似。



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值