您的位置:首页 > 其它

findViewById()与Inflate()和setContentView()关系扯谈

2014-01-21 21:16 423 查看
关于findViewById()与Inflate()和setContentView()的关系我理了理,清晰多了,觉得很有必要记一记。

1.findViewById()与Inflate()的关系
findViewById()其实好理解,从layout上把控件找出来并转为一个对应的对象。
至于Inflate()则是把layout从xml文件中实例化成一个对象。这样findViewById才能在上面找出控件。

2. Inflate()与setContentView()的关系
如果仅从上面这样看Inflate()的功能,setContentView()效果也是一样的。实际也上也是把xml文件上的layout实例化显示.
如: setContentView(R.layout.main);
不过setContentView()一运行,界面马上就显示。Inflate()则只生成和操作对象,但是隐藏状态,不显示在界面上。显示还是要靠setContentView()。

// LayoutInflater inflater=getLayoutInflater();
public class MyInflate extends Activity{
public void OnCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

//默认方法使用setContentView
//setContentView(R.layout.main);

//inflate()把布局实例化后,再显示在界面上
LayoutInflater inflate = LayoutInflater.from(this);
View vw = inflate.inflate(R.layout.main,null);
setContentView(vw);
}
}
3. 那Inflate()有什么价值呢?

       Inflate()主要用在当前Activity中,控制别的layout,Fragment就经常用。

public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)

inflater.inflate(R.layout.myfragment,container,false);
弹出窗口这类也是,通过Inflate()实现化出弹出窗口,然后再用findViewById()控制上面控件.

  其实这个和CS界面开发时的搞法差不多。

View dgVw=View.inflate(this,R.layout.dialog_layout,null);
TextView dgtv=(TextView)dgVw.findViewById(R.id.dgtv);
dgtv.setText("说好的年终奖呢?");
4.附注:    

 另外附上从http://www.2cto.com/kf/201205/131136.html找来的说明,

 这篇文章还进源码查看了一翻。发现其实本质都是调用context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES)方法得到的。

 实现LayoutInflater的实例化共有3种方法:
(1).通过SystemService获得

LayoutInflaterinflater = (LayoutInflater)context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES);

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

    (2).从给定的context中获得

        LayoutInflaterinflater = LayoutInflater.from(context);

        Viewview = inflater.inflate(R.layout.mian, null);

(3).

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

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

 Android关于这部份的源码:

LayoutInflater.from(context):
public static LayoutInflaterfrom(Context context) {
LayoutInflaterLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(LayoutInflater== null){
thrownew AssertionError("LayoutInflaternot found.");
}
returnLayoutInflater;
}


MAIL:  xcl_168@aliyun.com
BLOG: http://blog.csdn.net/xcl168
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息