以XML格式定义布局时以编程方式创建表行

Tor*_*ben 0 android tablelayout

我试图将行添加到我在XML文件中定义的TableLayout.XML文件包含表的标题行.

我可以使用各种教程中的信息很好地添加新行,但是为新行设置布局所需的代码是一个可怕的混乱,并且只要标题行的布局发生变化,维护就好了.

是否可以在仍然在XML中定义行布局的同时为TableLayout创建新行?例如,在XML中定义模板行,在代码中获取它的句柄,然后在需要时克隆模板.

或者是以某种方式完全不同的正确方法?

ada*_*amp 5

您提出的方法可以正常工作,它或多或少与填充ListView项目时使用的常用模式相匹配.

定义包含单行的布局.LayoutInflater通过使用获得LayoutInflater.from(myActivity).使用此inflater可以像使用模板一样使用布局创建新行.通常,您将希望使用3参数形式的LayoutInflater#inflate传递false作为第三个attachToRoot参数.

假设您想在每个项目中使用带有标签和按钮的模板布局.它可能看起来像这样:(虽然你的会定义你的表行.)

RES /布局/ item.xml:

<LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <TextView android:id="@+id/my_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    <Button android:id="@+id/my_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

然后在你膨胀的地方:

// Inflate the layout and find the component views to configure
final View item = inflater.inflate(R.layout.item, parentView, false);
final TextView label = (TextView) item.findViewById(R.id.my_label);
final Button button = (Button) item.findViewById(R.id.my_button);

// Configure component views
label.setText(labelText);
button.setText(buttonText);
button.setOnClickListener(buttonClickListener);

// Add to parent
parentView.addView(item);
Run Code Online (Sandbox Code Playgroud)