Android使用addView动态加载布局文件

第一步,要获取要将动态加载内容置入的容器 relativeLayout
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
第二步,获得要动态加载的布局文件
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.searchbox, null);
relativeLayout.addView(view);
第三步,动态载入
relativeLayout.addView(view);
看完整示例:
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
context = v.getContext();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.searchbox, null);
relativeLayout.addView(view);
ImageButton searchBoxBtn = (ImageButton) view
.findViewById(R.id.searchBoxBtn);
searchBoxBtn.setOnClickListener(new SearchBoxBtnOnClickListener(
relativeLayout, view, tv));
Toast.makeText(context, "searchBtn", Toast.LENGTH_SHORT).show();
}
});

你可能感兴趣的:(Android使用addView动态加载布局文件)