Android如何从代码中将Linearlayout添加到另一个LinearLayout

时间:2012-01-21 18:24:55

标签: java android android-linearlayout

我在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>

我制作了另一个名为item_box.xml的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中。我怎么能做到这一点?

4 个答案:

答案 0 :(得分:4)

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);

答案 1 :(得分:2)

在另一个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);

答案 2 :(得分:1)

你得到一个Nullpointer,因为linearLayout1不在mainLayout中。您需要先扩充视图然后添加它。您应该阅读此question我认为它会对您有所帮助。

答案 3 :(得分:1)

使用LayoutInflater

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemBox = inflater.inflate(R.layout.item_box);