【问题标题】:Inflate a layout into another layout (or convert the layout to a view and then inflate the view)将一个布局膨胀为另一个布局(或将布局转换为视图然后膨胀视图)
【发布时间】:2012-10-30 23:12:09
【问题描述】:

我想使用循环将一个布局多次膨胀到另一个布局中。当我为 TextView 或任何其他单个视图充气时,java 很好。但我想夸大整个布局。我为此使用什么方法,因为以下代码不起作用。 (就像我说的,循环和一切都很好,只是我不能为整个布局充气。我只知道如何为一个简单的视图充气)。

View childInflatedView = (View) theInflater.inflate(R.id.restaurant_displayed_on_list, null);
linLayout.addView(childInflatedView);
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="30dp"
android:orientation="horizontal"
android:background="@drawable/gradient_bg_hover"
android:id="@+id/restaurant_displayed_on_list" >

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_weight="6"
    android:layout_height="fill_parent"
    android:text="this is the inflated text"
    android:textColor="#990099"
    android:textSize="20dp"
    android:gravity="center_horizontal"

    />

<Button    
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="fill_parent"
android:background= "@drawable/delete"
/>
</LinearLayout>

编辑1:

正如 Matthew 所说,我认为解决方案是通过布局资源 ID 膨胀布局。 我认为问题在于上面没有显示的这行代码,因为布局无法转换为 TextView:

View categoryInflatedView1 = (View) theInflater.inflate(R.layout.categories_available, null);

((TextView) categoryInflatedView1).setText(category1);          

linLayout.addView(categoryInflatedView1);

如何访问位于布局内部的 TextView。我需要在充气之前编辑文本视图。

【问题讨论】:

    标签: java android xml


    【解决方案1】:

    您需要传入 layout 资源 ID。将 R.id.restaurant_displayed_on_list 替换为 R.layout.&lt;name of your layout file here&gt; 就可以了。

    【讨论】:

    • 这就是我之前所做的。我在想,因为它被投射到由于某种原因它不起作用的观点。也许布局不能被投射到查看????
    • 我被智障了。问题是我将布局转换为 (textview) 而不是首先通过 id 查找视图
    【解决方案2】:

    所以这不起作用的原因是 2 倍。

    您只需按照 Mathew 的说明通过布局资源 ID 扩展布局

    View childInflatedView = (View) theInflater.inflate(R.layout.restaurant_available, null);
    

    由于将布局转换为 TextView,我在日志中发现了一个额外的错误 相反,我必须使用此代码使其工作(布局变量然后按 id 查找视图):

    ((TextView) childInflatedView.findViewById(R.id.restaurant_displayed_on_list)).setText(currentlyDelRest1);
    

    虽然这个答案是正确的,但我将把接受的答案分配给马修,因为鉴于问题中提供的信息,他的答案是正确的。感谢您的帮助

    【讨论】:

      【解决方案3】:

      使用&lt;include&gt; 标签。它在现有布局中包含另一个 XML 布局。例如,添加以下两行将在您的父布局中包含另外两个布局:

       <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
      <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
      

      只有 layout 属性是必需的。这个属性,没有 android 命名空间前缀,是对你想要扩展的布局文件的引用。也可以使用android:id指定包含布局的根视图的id;如果定义了一个,它还将覆盖包含布局的 id。同样,您可以覆盖所有布局参数。

      【讨论】:

      • 所以你是说用它在 XML 中包含另一个视图?问题是我必须遍历未知数量的对象,然后根据这些对象扩展视图。我不能只说“包括 7 个项目”。关于如何继续为实际布局文件而不是视图继续布局充气器的任何建议?
      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多