安卓编程错误

3
我正在使用Eclipse Galileo完成Android“Hello, Testing”教程。当我尝试编译并运行程序时,出现了一个错误,提示“com.example.helloandroid.R.id无法解析”。请参考http://developer.android.com/resources/tutorials/testing/helloandroid_test.html
package com.example.helloandroid.test;  
import com.example.helloandroid.HelloAndroid;  
import android.test.ActivityInstrumentationTestCase2;  
import android.widget.TextView;

public class HelloAndroidTest extends ActivityInstrumentationTestCase2<HelloAndroid>  
{    
    private HelloAndroid mActivity;  // the activity under test    
    private TextView mView;          // the activity's TextView (the only view)    
    private String resourceString;    

    public HelloAndroidTest() 
    {      
        super("com.example.helloandroid", HelloAndroid.class);    
    }    

    @Override    
    protected void setUp() throws Exception 
    {        
        super.setUp();        
        mActivity = this.getActivity();        
        mView = (TextView) mActivity.findViewById(com.example.helloandroid.R.id.textview);        
        resourceString = mActivity.getString(com.example.helloandroid.R.string.hello);    
    }    

    public void testPreconditions() 
    {      
        assertNotNull(mView);    
    }    

    public void testText() 
    {      
        assertEquals(resourceString,(String)mView.getText());    
    }
}  

感谢您能提供任何帮助和建议!

2
请发布您的整个代码。您可能缺少一个导入。 - wkl
2个回答

4

有时候即使没有做错什么,这种情况似乎也会随机发生,因此首先尝试清理项目以强制进行完整的重建和R.java的重新生成。

如果这样做无法修复问题,您可能需要重新开始,并确保您严格遵循项目设置的说明。您对com.example.helloandroid.R的明确引用要求您的项目被命名为该名称,而不是com.example.HelloAndroidTest,因为如果它是您的主类,则可能会以这种方式结束。如果您打开gen/文件夹并看到一个不在com.example.helloandroid包中的.R.java文件,那就是您的问题所在——生成的R类的包和您引用它的绝对或相对名称需要匹配。


我还注意到它给了我快速修复建议:在类型“R”中创建字段类型“id”,并在类型“R”中创建常量“id”。 - androidGM
听起来你可能缺少一个XML文件或将其与错误的包相关联。 - Chris Stratton
原来在我的Hello Android项目的main.xml中TextView的id从未被识别,因此在com.example.helloandroid.R中也没有创建id。谢谢您的帮助! - androidGM

1

编辑HelloAndroid项目中的R.java文件(位于gen目录下),而不是HelloAndroidTest项目。找到以下代码块

<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
/>

这里的问题是没有指定id。只需添加即可。

android.id:"@+id/textview"

i.e

<TextView  
    android:id="@+id/textview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接