我想一次又一次地重用现有布局,而不是创建/编写新的 xml。目前,我有这样的。
我想以编程方式实现这样的功能,而不是用 xml 编写(可能我想在 Activity 中编写它)。
我可以知道该怎么做吗?另外,另一个问题是,如果我像这样重用,“id”将是相同的。如果是这样,我该如何设置文本?
最佳答案
将 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/