android - 以编程方式为 Android 布局充气

标签 android xml layout layout-inflater

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

enter image description here

我想以编程方式实现这样的功能,而不是用 xml 编写(可能我想在 Activity 中编写它)。

enter image description here

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

enter image description here

最佳答案

将 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");
}

Also, another problem is that if I reuse like that, "id" will be same. If so, how can I set text?

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

descriptionLayout.findViewById(R.id.text_view);

不是这样的:

findViewById(R.id.text_view);

关于android - 以编程方式为 Android 布局充气,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28422546/

相关文章:

android - 使图像适合整个 imageView 然后动画显示隐藏的部分

xml - 用于 Hudson 摄取的 Android InstrumentationTestRunner XML 输出

CSS float 。有可能中断流量吗?

layout - 引入错误处理时如何保持代码布局可视化 'attractive'?

java - JPanel 中的 JPanel

javascript - 打开 Intent 时“导航被阻止”

android - 如何将 Azure 通知中心迁移到 Firebase 云消息传递?

Android - 菜单项无法解析为 onOptionsItemSelected() 中的类型

xml - 是否有相当于图像的 .svg 的视频格式?

c# - 如何在 C# 中将 XDocument 附加到 MailMessage?