仍然无法在Android中添加按钮到布局

时间:2012-09-03 18:07:44

标签: android android-layout

我刚刚启动了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>

3 个答案:

答案 0 :(得分:2)

尝试为布局分配ID,然后将按钮添加到布局中。

我很确定这2个布局是不一样的,所以你实际上是在一个永远不会显示的布局上添加一个按钮。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LinearLayout layout = (LinearLayout) findViewById(R.id.lnr_main);

    Button btn = new Button(this);
    btn.setId(123);
    btn.setText("Welcome to WI FI World");
    layout.addView(btn);
}

为布局分配了ID

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/lnr_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >

</LinearLayout>

答案 1 :(得分:1)

为你的linearLayout提供一个id。

然后在你的代码中

LinearLayout layout = (LinearLayout)findViewById(R.id.given_id);

保持其余部分相同,应该有效。

答案 2 :(得分:1)

在XML中使用Id的LinearLayout,在jave代码中使用XML中的LinearLayout的id

<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"
    android:id="@+id/linear" >

</LinearLayout>

在onCreate()中:

LinearLayout linear=(LinearLayout)findViewById(R.id.linear);

 //Select widgets
 linear.addView()