IntelliJ IDEA 13新建安卓工程之后打开R文件发现没有内容.

pedoc 2014-01-29 07:08:32
RT.
升级到IntelliJ IDEA 13之后,新建安卓工程,编译之后一切正常,也能够在虚拟机和真机上运行.但是,在main.xml里面定义了一个Button之后通过findViewById进行查找却没有找到Button导致null指针异常.然后定位到R.java发现这个文件的内容如下:
/*___Generated_by_IDEA___*/

package com.example.Test;

/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
public final class R {

}
根本没有看到id.attr什么的定义.
mail.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"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
android:id="@+id/mButton"
/>
</LinearLayout>

MyActivity.java内容如下:
public class MyActivity extends Activity
{
private Button mButton;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mButton=(Button)findViewById(R.id.mButton); //此处运行的时候,mButton会是null.
setContentView(R.layout.main);
}
}

奇怪的是:
(1)
R.id.mButton是可以的,但是Ctrl+B转到定义的时候却不是跳转到R.id.mButton=xxx那里.而是跳转到main.xml里面的android:id="@+id/mButton".
(2)
即使是这样,编译没有错误,也能在机器上运行.

请高手指点一下为什么?
...全文
1204 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
小白大大-- 2014-10-29
  • 打赏
  • 举报
回复
我也遇到楼主问题了,一切正常就是R文件是空的
pedoc 2014-01-31
  • 打赏
  • 举报
回复
引用 2 楼 geniuslt 的回复:
把setContentView放到前面去,这样: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton=(Button)findViewById(R.id.mButton); } setContentView会把xml资源绑定到Activity上,此后才能直接做find操作,否则一定是空的
感谢指点.NULL的问题解决了,的却是这样.但是,IDEA里边的R文件的内容始终为空是什么情况?如下: /*___Generated_by_IDEA___*/ package com.example.App; /* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */ public final class R { } 在eclipse中,R文件里面会有好几个静态类.比如id,attr什么的.这里虽然没有,但是也不会报错,程序同样运行正常.请指点
geniuslt 2014-01-30
  • 打赏
  • 举报
回复
把setContentView放到前面去,这样: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton=(Button)findViewById(R.id.mButton); } setContentView会把xml资源绑定到Activity上,此后才能直接做find操作,否则一定是空的
pedoc 2014-01-29
  • 打赏
  • 举报
回复
补充一下,如果代码改一下: mButton=(Button)findViewById(R.id.mButton); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //do something } }); 此时就会因为findViewById并没有找到正确的资源,导致mButton=null,setOnClickListener会引发NullException.

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧