【原创】Android多个xml文件的使用

Android中经常会使用多个xml文件,但在Mainactivity中使用的setContentView(R.layout.main)只加载main.xml文件,其他xml文件不加载进当前视图,当我们要用到其他xml文件中的控件是发现直接使用findViewById()方法时不报错但控件的值找不到为null,而一旦为该控件添加相应事件就会出现空指针异常。原因就在于控件并未加载进当前视图。

解决方法:两种

1、使用在main.xml中使用include语句

         <include layout="@layout/x"/>

2、使用LayoutInflater 举个简单;例子

两个xml文件main.xml和x.xml

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>

x.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <Button 
       android:id="@+id/bt"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       
       android:layout_below="@id/tv"
       />

</RelativeLayout>

 

activity中的代码:

package leemo.e;


import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class EeeActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		TextView tv = (TextView) findViewById(R.id.tv);
		tv.setText("content is change");
		
		
		LayoutInflater layout=this.getLayoutInflater();
		View view=layout.inflate(R.layout.x,null);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(  
				LinearLayout.LayoutParams.FILL_PARENT,  
				LinearLayout.LayoutParams.WRAP_CONTENT);
				addContentView(view,params);
		Button bt = (Button) view.findViewById(R.id.bt);
		bt.setText("µã»÷ÎÒ ");
		bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(EeeActivity.this, "button click",
						Toast.LENGTH_SHORT).show();
			}
		});
		
	}
	
}
这样也能达到同样的效果 ,不过发现个问题,控件的位置不好控制,留待以后吧。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值