LayoutInflater作用是将layout的xml布局文件实例化为View类对象。
LayoutInflater在Android中是“扩展”的意思,作用类似于findViewById(),不同的是LayoutInflater是用来获得布局文件对象的,而findViewById()是用来获得具体控件的。LayoutInflater经常在BaseAdapter的getView方法中用到,用来获取整个View并返回。
获取LayoutInflater有三种方法:
LayoutInflater inflate = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
LayoutInflater inflate = getLayoutInflater();//在Activity中使用
LayoutInflater inflate = LayoutInflater.from(getApplicationContext());
用法举例:
user_folder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
MainActivity.java:
package com.example.hello;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
private RelativeLayout frame;
private View mySelfView1 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frame = (RelativeLayout) findViewById(R.id.frame);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
// 第一种方式
// LayoutInflater inflate = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// 第二种方式
// LayoutInflater inflate = getLayoutInflater();
LayoutInflater inflate = LayoutInflater.from(getApplicationContext());
mySelfView1 = inflate.inflate(R.layout.user_folder, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mySelfView1 != null){
Toast.makeText(getApplicationContext(), "show my selfview", Toast.LENGTH_SHORT).show();
frame.addView(mySelfView1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
frame.removeView(mySelfView1);
}
}, 2000);
} else {
Toast.makeText(getApplicationContext(), "selfview is null", Toast.LENGTH_SHORT).show();
}
}
}