【发布时间】:2012-09-03 18:07:43
【问题描述】:
我刚开始使用 android,并在此处发布之前尝试了以下问题以获得此答案:
Android - Adding layout at runtime to main layout
Add button to a layout programmatically
Dynamically adding a child to LinearLayout with getting each child's position
我仍然无法将按钮添加到线性布局:(
以下是活动代码,请告诉我哪里错了:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.activity_main, null);
Button btn = new Button(this);
btn.setId(123);
btn.setText("Welcome to WI FI World");
layout.addView(btn);
}
xml 如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
【问题讨论】:
-
您需要将线性布局添加到页面中。我很确定那些不是相同的线性布局。因此,您正在向未显示的按钮添加一个按钮