簡體   English   中英

Android如何從代碼向另一個LinearLayout添加Linearlayout

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM