首页 > 移动平台 > 详细

android学习—— LayoutInflater的使用

时间:2014-02-07 14:21:59      阅读:370      评论:0      收藏:0      [点我收藏+]

  在实际开发种LayoutInflater这个类还是非常有用的,它的作用类似于findViewById(),不同点是LayoutInflater是 用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体widget控件 (如:Button,TextView等)。
 获取LayoutInflater的方法有如下三种:

   第一种:

bubuko.com,布布扣
1 LayoutInflater inflater = LayoutInflater.from(this);  
2 View layout = inflater.inflate(R.layout.main, null); 
View Code

 第二种:仅在继承activity的情况下使用。

bubuko.com,布布扣
1     LayoutInflater inflater = getLayoutInflater();  
2     View layout = inflater.inflate(R.layout.main, null);  
View Code

 第三种:

bubuko.com,布布扣
1 LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  
2 View layout = inflater.inflate(R.layout.main, null); 
View Code

实例:

bubuko.com,布布扣
 1     public class LayoutInflaterActivity extends Activity {  
 2         private EditText et;  
 3         private Button btn;  
 4       
 5         @Override  
 6         public void onCreate(Bundle savedInstanceState) {  
 7             super.onCreate(savedInstanceState);  
 8             // 第一种方法  
 9             LayoutInflater inflater = LayoutInflater.from(this);  
10             View layout = inflater.inflate(R.layout.main, null);  
11             // 第二种方法  
12             // LayoutInflater inflater = getLayoutInflater();  
13             // View layout = inflater.inflate(R.layout.main, null);  
14             // 第三种方法  
15             // LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
16             // View layout = inflater.inflate(R.layout.main, null);  
17             // 这里是通过事先获得的布局文件来实例化具体控件,并且可以根据情况自定义控件  
18             et = (EditText) layout.findViewById(R.id.edittext);  
19             et.setBackgroundColor(Color.YELLOW);  
20             btn = (Button) layout.findViewById(R.id.btn);  
21             btn.setBackgroundColor(Color.CYAN);  
22             // 显示  
23             setContentView(layout);  
24         }  
25     }  
View Code

 

 

android学习—— LayoutInflater的使用

原文:http://www.cnblogs.com/nanxiaojue/p/3539186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!