【问题标题】:Still Can't Add Button to Layout in Android仍然无法在 Android 中将按钮添加到布局中
【发布时间】: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>

【问题讨论】:

  • 您需要将线性布局添加到页面中。我很确定那些不是相同的线性布局。因此,您正在向未显示的按钮添加一个按钮

标签: android android-layout


【解决方案1】:

尝试为您的布局分配一个 id,然后将按钮添加到布局中。

我很确定这两种布局不一样,所以你实际上是在向从未显示的布局中添加一个按钮。

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);
}

为 Layout 分配了一个 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>

【讨论】:

    【解决方案2】:

    在 XML 中获取 LinearLayout 的 ID,在 java 代码中使用 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()
    

    【讨论】:

      【解决方案3】:

      给你的linearLayout一个id。

      然后在你的代码中

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

      其余部分保持不变,应该可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-28
        • 1970-01-01
        • 2017-05-31
        • 2011-10-19
        • 2014-03-30
        • 1970-01-01
        相关资源
        最近更新 更多