gpt4 book ai didi

android - r.id 没有重新生成

转载 作者:搜寻专家 更新时间:2023-11-01 07:40:43 26 4
gpt4 key购买 nike

我正在尝试创建一个简单的按钮示例,但是当我添加此代码时:

mButton = (Button) findViewById(R.id.button1);

它不会更新我的 R.id 文件。我已经尝试了一切,包括确保自动构建开启、清理项目和更新 SDK。这在 1.6 和 2.2 项目中都会发生。

完整代码如下:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class NewTest extends Activity {

Button myButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.button1);
}
}

最佳答案

findViewById 正在查看您引用的位置的 R.id 文件。

您的代码不会导致文件更新,因为它只是在寻找按钮。

在布局中创建按钮将导致 R.id 文件更新。

<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button One"/>

由于您在上下文中使用 findViewById,并且当前上下文的 View 是 main.xml,因此上面的按钮示例需要位于 main.xml 文件中。否则,如果您在另一个 .xml 布局中有另一个同名按钮,该条目将在您的 R.id 文件中创建,但您的代码会给您一个空指针异常,因为该按钮在您所在的上下文中不存在试图从中引用它。

关于android - r.id 没有重新生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com