`

android中LayoutInflater

 
阅读更多
转自:http://dev.10086.cn/cmdn/wiki/index.php?doc-view-6066.html
Inflater英文意思是膨胀,在Android中应该是扩展的意思吧。
LayoutInflater的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化!而 findViewById()是找具体某一个xml下的具体 widget控件(如:Button,TextView等)。

她可以有很多地方可以使用,如BaseAdapter的getView中,自定义Dialog中取得view中的组件widget等等。

它的用法有2种:

第一种方式:

package org.hwq.layoutinflater;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {
	EditText et;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //LayoutInflater第一种使用方式
        LayoutInflater inflater = LayoutInflater.from(this);
        //取出main.xml实例的view
        View view = inflater.inflate(R.layout.main, null);
        //这里以前我们是使用了:this.findViewById(R.id.editText1);
        et = (EditText) view.findViewById(R.id.editText1);
        Toast.makeText(this, et.getHint(),0).show();
    }
}


第二种方式:

package org.hwq.layoutinflater;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {
	EditText et;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //LayoutInflater第二种使用方式
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        //取出main.xml实例的view
        View view = inflater.inflate(R.layout.main, null);
        //这里以前我们是使用了:this.findViewById(R.id.editText1);
        et = (EditText) view.findViewById(R.id.editText1);
        Toast.makeText(this, et.getHint(),0).show();
    }
}


对比发现其实就改了一行。
LayoutInflater inflater = LayoutInflater.from(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

查看源代码你会发现LayoutInflater.from()方法调用如下:
public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics