[英]Android how to add a Linearlayout to another LinearLayout from code
我在main.xml中有一个LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/mainLayout" >
</LinearLayout>
我制作了另一个XML文件,称为item_box.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/item_bg"
android:gravity="right" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:text="@string/item1"
android:textSize="30dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:gravity="right"
android:text="@string/number1"
android:textColor="@color/number_bg"
android:textSize="30dp" />
</LinearLayout>
基本上,我想从代码中(以编程方式)执行的操作是将几个item_box.xml添加到main.xml中。 我该怎么做?
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemBox = inflater.inflate(R.layout.item_box);
mainLayout.addView(itemBox);
尝试在另一个linearlayout内添加这个linearlayout,将id添加到linearlayout layout1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/firstlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
在oncreate()调用中
LinearLayout firstlayout=(LinearLayout)findviewbyId(R.id.firstlayout);
LinearLayout secondlayoout=(LinearLayout)this.getLayoutInflater().inflate(R.layout.layout2,null); //inflating view from xml
TextView btn1=(TextView)secondlayoout.findviewbyId(R.id.button1);
btn1.settext("TEST");
firstlayout.addview(secondlayoout);
您正在获取Nullpointer,因为linearLayout1不在mainLayout中。 您需要先膨胀视图,然后添加它。 您应该阅读此问题,我认为它将对您有所帮助。
使用LayoutInflater
:
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemBox = inflater.inflate(R.layout.item_box);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.