以程序方式向LinearLayout添加多个零部件



我正在尝试用程序将多个组件添加到线性布局中。以下是代码:

private View createCalloutView(Graphic graphic) {
    LinearLayout ret = new LinearLayout(this);
    ret.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    TextView reportContent = new TextView(this);
    reportContent.setText(eventName + "n" + eventBy + "n" + eventAddress + "n" + eventDesc
            + "n" + eventDate + "n" + eventTime);
    reportContent.setTextColor(Color.BLACK);
    reportContent.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
    reportContent.setPadding(1, 0, 1, 0);
    Button viewDtlEventBtn = new Button(this);
    viewDtlEventBtn.setText("View details");
    viewDtlEventBtn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
            LayoutParams.WRAP_CONTENT));
    ret.addView(reportContent);
    ret.addView(viewDtlEventBtn);
    return ret;
}

有了这些代码,我只看到了文本视图,我的按钮不见了。有什么想法吗?提前谢谢。

这取决于您希望如何排列LinearLayout中的项目。如果您想将按钮排列在TextView旁边,那么按钮宽度可能应该是WRAP_CONTENT而不是FILL_PARENT。如果您想在TextView下显示按钮,那么您的LinearLayout应该将vertical作为orientation(默认为horizontal)。Imo,最简单的方法是在xml文件中定义布局。至少您可以在编译时看到输出,并在运行时使用充气程序检索View的对象

线性布局的默认方向是水平的。您需要先设置方向。

LinearLayout ret = new LinearLayout(this);
ret.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT));
ret.setOrientation(LinearLayout.VERTICAL);

这将解决您丢失按钮的问题。

您忘记为线性布局设置布局方向,只需将其设置如下:

ret.setOrientation(LinearLayout.VERTICAL);

最新更新