【问题标题】:Creating table rows programmatically while defining layout in XML在 XML 中定义布局时以编程方式创建表行
【发布时间】:2011-11-27 02:28:09
【问题描述】:

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

我可以使用各种教程中的信息很好地添加新行,但是为新行设置布局所需的代码非常混乱,而且每当标题行的布局时维护起来似乎很麻烦变化。

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

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

【问题讨论】:

    标签: android tablelayout


    【解决方案1】:

    您提出的方法可以正常工作,并且或多或少符合填充 ListView 项目时使用的常见模式。

    定义一个包含单行的布局。使用LayoutInflater.from(myActivity) 获取LayoutInflater。使用此充气器使用您的布局(如模板)创建新行。通常您会希望使用LayoutInflater#inflate 的三参数形式,将false 传递给第三个attachToRoot 参数。

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

    res/layout/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>
    

    然后在你充气的地方:

    // 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2012-10-01
      • 1970-01-01
      • 2012-08-07
      相关资源
      最近更新 更多