【问题标题】:Inflate programmatically for android layout以编程方式为 android 布局充气
【发布时间】:2025-12-31 04:05:16
【问题描述】:

我想一次又一次地重用现有布局,而不是创建/编写新的 xml。目前,我有这样的。

我希望以编程方式而不是用 xml 编写(可能是我想在 Activity 中编写)。

我可以知道怎么做吗?另外,另一个问题是,如果我这样重用,“id”将是相同的。如果可以,如何设置文字?

【问题讨论】:

    标签: android xml layout layout-inflater


    【解决方案1】:

    在你的布局中添加一个LinearLayout,然后在代码中多次膨胀header_description布局并添加到LinearLayout中。

    将布局更改为与此类似:

    <include layout="@layout/header_list_image"/>
    
    <LinearLayout
        android:layout_id="@+id/description_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_contents"
        android:orientation="vertical" >
    
    <include layout="@layout/header_url"/>
    <include layout="@layout/row_listing_like_comment_share"/>
    <include layout="@layout/header_comment_separator"/>
    

    在代码中,使用 id 找到 LinearLayout,并一次添加一个描述布局并将它们添加到您的 onCreate() 函数中:

    LinearLayout layout = (LinearLayout)findViewById(R.id.description_layout);
    LayoutInflater inflater = getLayoutInflater();
    
    // add description layouts:
    for(int i = 0; i < count; i++)
    {
         // inflate the header description layout and add it to the linear layout:
         View descriptionLayout = inflater.inflate(R.layout.header_description, null, false);
         layout.addView(descriptionLayout);
    
         // you can set text here too:
         TextView textView = descriptionLayout.findViewById(R.id.text_view);
         textView.setText("some text");
    }
    

    另外,另一个问题是,如果我这样重用,“id”将是相同的。如果是这样,我该如何设置文本?

    在膨胀的布局上调用 findViewById() 例如:

    descriptionLayout.findViewById(R.id.text_view);
    

    不是这样的:

    findViewById(R.id.text_view);
    

    【讨论】: