![](/img/trans.png)
[英]TextView not appearing when programatically adding it to a LinearLayout
[英]Adding Multiple Components to LinearLayout Programatically
我正在嘗試以編程方式將多個組件添加到線性布局中。 以下是代碼:
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;
}
使用這些代碼,我只希望看到textview並且我的按鈕丟失了。 有任何想法嗎? 提前致謝。
這取決於您要如何在LinearLayout
安排項目。 如果要在TextView
旁邊排列按鈕,則按鈕寬度可能應該是WRAP_CONTENT
而不是FILL_PARENT
。 如果要在TextView
下顯示按鈕,則LinearLayout
orientation
應為vertical
(默認為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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.