【问题标题】:Adding a button添加按钮
【发布时间】:2013-06-02 09:01:34
【问题描述】:

我想创建一个新按钮。这段代码在我的 MainActivity 中。

public void method1 (View view)
{
    Button myButton = new Button(this);
    myButton.setText("Press Me");
    LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
    layout.addView(myButton);
}

我在R.id.layout 上收到一个错误,说layoutcan´t be resolve or is not a field。我该如何解决?我是安卓新手。

//编辑 我的 acitvity_main.xml 看起来像这样

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:onClick="neuerTrainingsplan"
    android:text="@string/neuerPlan" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/button2"
    android:layout_alignBottom="@+id/button2"
    android:layout_toLeftOf="@+id/button2"
    android:onClick="TrainingsplanAbrufen"
    android:text="@string/TrainingsplanAbrufen" />

【问题讨论】:

  • 如果不显示更多代码,几乎不可能给出准确的答案。在您调用 setContentView(...) 的位置发布代码,并发布您的 XML 布局文件。
  • This question 看起来和你的一样。并确保您在 Activity 的onCreate() 中有此代码。
  • 执行上述操作,您需要为布局分配一个 id。将此添加到您的 .xml 文件 android:id="@+id/layout1"

标签: android eclipse button


【解决方案1】:

该错误表示您尚未声明 ID 为 layout1 的布局。如果您检查了从您的班级导入以导入正确的R 班级。应该是yourpackage.R 而不是android.R

【讨论】:

  • 我没有声明它:(。我必须在哪里声明它,我该怎么做?
  • 在您作为参数传递给 setContentView 的同一布局中
  • @blackbelt :不建议人们导入自己的包的 R.java。它是隐式完成的。
  • @Squonk 这并不总是正确的。有时 eclipse 导入 android.R 一个,我看到很多人问为什么你不能引用他们的 id,当他们实际声明它时
  • @blackbelt :我不是在谈论导入android.R 的场景(不应该这样做)。我的意思是没有必要为您自己的包显式导入R.java。如果您使用不同的包,您可能需要这样做,但主包中的任何 Android 类都将隐式访问 R 类,而无需导入它,如果显式导入它可能会出现问题。
【解决方案2】:

确保您在 xml 文件中进行了线性布局。它的 android:id 是 layout1。

<LinearLayout android:id="@+id/layout1" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" />

在你的布局文件中添加这个。

【讨论】:

  • 你会在哪里添加它?我对此真的很陌生:S
  • 在您的布局文件中。你在 setcontentview(layoutfile.xml) 中使用的
  • 我在 activity_main.xml 文件中添加了它,它说,
  • 使用 android:orientation="vertical"
  • 它仍然说没有指定方向:/
猜你喜欢
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
  • 2018-06-04
相关资源
最近更新 更多