gpt4 book ai didi

java - Findviewbyid 找不到按钮

转载 作者:行者123 更新时间:2023-12-01 17:18:26 26 4
gpt4 key购买 nike

我是 Android 编程新手,所以我有一个简单的问题!我在 activity_main.xmlmain_activity.java 中创建了一个 button 我想通过调用 findbyviewid() 使用此按钮code> 但当我编写它时,它在 activity_main.xml 中找不到我的按钮! 这是代码: 包 com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=findViewById(R.layout.button1);//this is where i get error message that can't find my button

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

那么我的问题是什么?

谢谢!!!

最佳答案

试试这个:

Button btn = (Button)findViewById(R.id.button);

findViewById 将返回一个 View 对象,您必须将其向下转换为 Button 对象。

关于java - Findviewbyid 找不到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452761/

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