您的位置:首页 > 移动开发 > Android开发

android学习—— LayoutInflater的使用

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

第一种:

public class LayoutInflaterActivity extends Activity {
private EditText et;
private Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 第一种方法
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);
// 第二种方法
// LayoutInflater inflater = getLayoutInflater();
// View layout = inflater.inflate(R.layout.main, null);
// 第三种方法
// LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
// View layout = inflater.inflate(R.layout.main, null);
// 这里是通过事先获得的布局文件来实例化具体控件,并且可以根据情况自定义控件
et = (EditText) layout.findViewById(R.id.edittext);
et.setBackgroundColor(Color.YELLOW);
btn = (Button) layout.findViewById(R.id.btn);
btn.setBackgroundColor(Color.CYAN);
// 显示
setContentView(layout);
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: