1

我有一个自定义视图(扩展视图),我想在 OnCreate 函数中添加控件(按钮/文本框等),以便在运行时将这些组件添加到视图中:

public Section(Context context) {
    super(context);

    this.setBackgroundColor(Color.argb(255, 242, 242, 242));
    this.setOnTouchListener(mSectionOnTouch);

    LinearLayout l = new LinearLayout(this.getContext());
    l.setOrientation(LinearLayout.VERTICAL);
    Button btn = new Button(this.getContext());
    btn.setId(1);
    btn.setText("btn1");
    l.addView(btn);

    Button btn2 = new Button(this.getContext());
    btn2.setId(2);
    btn2.setText("btn2");
    l.addView(btn2);

} // Section

但这似乎没有任何作用......有人可以告诉我我做错了什么吗?

非常感谢

FR

4

1 回答 1

0

您永远不会添加l到您的视图中。它应该如下所示:

public Section(Context context)
{
    // setup linear layout

    addView(l);
}

一个稍微简单的方法是让您的自定义视图扩展 LinearLayout。然后您可以直接将视图添加到您的自定义视图中,而不必嵌套另一个容器,这对性能更好。

于 2012-11-14T17:11:53.917 回答