.在做项目的工程中,经常会用到一些相同的背景框,但是前景的选择不同。这个时候可以使用LayoutInflater来实现。
代码如下:
main.xml
inflater.xml
inflater2,xml
background.xml
java代码部分:
InflaterActivity,java
package fover.inflater;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class InflaterActivity extends Activity implements OnClickListener { private Button button1; private Button button2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findView(); setOnclick(); } /** * 描述:设置监听事件 */ private void setOnclick() { button1.setOnClickListener(this); button2.setOnClickListener(this); } /** * 描述:发现各种VIEW */ private void findView() { button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: Intent intent=new Intent(InflaterActivity.this, personal.class); startActivity(intent); break; case R.id.button2: Intent intent2=new Intent(InflaterActivity.this, rank.class); startActivity(intent2); break; default: break; } }}personal.java
package fover.inflater;import android.app.Activity;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup.LayoutParams;import android.view.Window;import android.widget.LinearLayout;public class personal extends Activity { private View inflaterView; private LinearLayout bgView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.background); bgView=(LinearLayout)findViewById(R.id.bglayout); LayoutInflater inflater=LayoutInflater.from(this); inflaterView=inflater.inflate(R.layout.inflater, null); bgView.addView(inflaterView,new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); }}rank.java
package fover.inflater;import android.app.Activity;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup.LayoutParams;import android.view.Window;import android.widget.LinearLayout;public class rank extends Activity { private LinearLayout bigView; private View inflaterView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.background); bigView=(LinearLayout)findViewById(R.id.bglayout); LayoutInflater inflater=LayoutInflater.from(this); inflaterView=inflater.inflate(R.layout.inflater2, null); bigView.addView(inflaterView,new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); }}需要注意的是需要在:AndroidManifest.xml设置权限哦。
运行效果截图: