Java findViewById返回一个错误
findViewById给出了一个错误,我认为这是因为它返回null。我的应用程序被迫关闭Java findViewById返回一个错误,java,android,textview,Java,Android,Textview,findViewById给出了一个错误,我认为这是因为它返回null。我的应用程序被迫关闭 SensorManager sensorManager=null; TextView x= null; TextView y= null; TextView z= null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) {
SensorManager sensorManager=null;
TextView x= null;
TextView y= null;
TextView z= null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
x= (TextView) findViewById(R.id.tv1);
y= (TextView) findViewById(R.id.tv2);
z= (TextView) findViewById(R.id.tv3);
}
XML:
有人能告诉我我做错了什么吗
解决了
我使用了Sunny在底部给出的XML!谢谢大家 这很简单。。。。电视*不在您的布局中
请发布布局,我100%确定它不包含:
<TextView android:id="@+id/tv1"/>
<TextView android:id="@+id/tv2"/>
<TextView android:id="@+id/tv3"/>
在进一步进行android开发之前,还请学习如何获得logcat!;-)
Window->Show View->Logcat首先:验证您的
TextView
是否存在于布局中:main.xml
:
<TextView android:id="@+id/tv1" .../>
<TextView android:id="@+id/tv2" .../>
<TextView android:id="@+id/tv3" .../>
第二步:按照以下步骤重建您的项目:项目==>清理==>选择您的项目并单击“确定”。是上述代码工作正常,xml文件应如下所示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView>
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
android:id=“@+id/tv3”
android:layout\u width=“包装内容”
android:layout\u height=“wrap\u content”>
是的,解决了这个问题,如果没有处理xml,那么
导入android.R;
因此,如果您有xml,它将给出错误
去掉那个
和进口PACKAGENAME.R 发生这种情况的原因是:
findViewById()
将在由setContentView(R.layout.main)
建立的视图层次结构中搜索文本视图。因此,如果文本视图不在main.xml中,您将得到一个空值,它是tv1
,tv2
和tv3
在主布局xml中正确声明的?Help?
显示您的错误日志,并且您的xml布局也已添加了3个文本视图,其中包含xml中的ID。对不起,我怎么看LogCat?LogCat是你在思考编程和提问之前必须使用的东西。没有它,你就完全看不到你的代码。要显示:add view->logcat您现在明白了,并且您已经删除了您的帖子:),您应该让它显示,以便其他人可以从中获取信息:)我尝试使用它作为我的XML,它成功了!非常感谢您,先生!如果我在发布之前已经添加了一个XML,我将再次编辑它:D
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView>
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>