我们知道在Android中通过布局文件来描述软件的界面,而通常在Activity中都是使用setContentView()来将布局显示出来。但是如果我们在非Activity的情况下,而且需要对布局中的控件进行设置等操作,该如何处理呢?这就需要使用到动态加载布局 LayoutInflater,下面ATAAW.COM来做介绍。
以一个简单布局example.xml为例,里面只有一个按钮和一个文本显示框控件。
< TextView
android:id="@+id/tview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ATAAW.COM"
/>
< Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="按钮"
/>
在程序中动态加载以上布局。
LayoutInflater flater = LayoutInflater.from(this);
View view = flater.inflate(R.layout.example, null);
获取布局中的控件。
button = (Button) view.findViewById(R.id.button);
textView = (TextView)view.findViewById(R.id.tview);
为Button添加事件监听。
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
textView.setText("WWW.ATAAW.COM");
}
});
一般情况下,LayoutInflater在定义适配器中使用的比较多,例如我们可以为适配器定义布局,继而在适配器的设计中对控件进行数据绑定等设置操作。
如果没有利用以上直接加载布局的方法,我们还可以直接new一个view来使用,然后用setLayoutParams来设置具体的布局情况,具体代码如下: imgView=newImageView(context);
imgView.setLayoutParams(newLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
imgView.setScaleType(ScaleType.FIT_XY);
imgView.setImageResource(drawableRourcesId);
handler.sendEmptyMessageDelayed(1, 10);
这里的drawableRourcesId实际上是一个图片,如果还要添加监听事件可以写成:
imgView.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
windowManager.removeView(imgView);//这里的windowManager我在另一篇文章里面写过,事实上这里说的这么多都是建立在这个上面的,就是当我们把这个View拿到手怎么显示在屏幕上呢?就是用的这个windowManager。}});