[英]findViewById returns null - Android - setContentView
[英]setContentView() returns null if raw resource folder is not empty
我的主要活動是開始兒童活動。 在孩子的onCreate()
我稱:
setContentView(R.layout.console);
TextView tv = (TextView)findViewById(R.id.console);
只要我的原始資源文件夾為空,就可以找到該文件。 當我將任何文件放入其中時, findViewById()
返回null
。 我不知道為什么原始文件夾中的文件之間存在干擾,而缺乏查找布局資源的原因。
我嘗試使用NetBeans和Eclipse進行構建,R.java包含所有必需的條目,並且沒有ID沖突。 如果我在原始文件夾中添加文件,則文件ID將正確添加到R.java中,並且沒有其他更改。
在LogCat中,嘗試使用TextView電視時,我立即得到一個空指針異常。 當我在聲明/初始化之后立即將tv的值寫入日志時,tv是空引用。
@Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i("Calling onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.console);
TextView tv = (TextView)findViewById(R.id.console);
Log.i("tv = " + tv);
}
這似乎是一個問題,因為該活動由MAIN活動與
Intent intent = new Intent(getContext(), ConsoleActivity.class);
int requestCode = Activity.RESULT_OK;
startActivityForResult(intent, requestCode);
控制台活動的布局文件console.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">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/console"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</ScrollView>
</LinearLayout>
</LinearLayout>
我找到了解決方法。 該代碼是庫的一部分。 在庫項目中,我沒有包括原始資源目錄,因為我不在庫中使用原始資源。 現在,我在庫項目中創建了一個包含一些(虛擬)文件的原始目錄,並且...在apps項目中添加了一個包含文件的原始目錄時,空指針錯誤奇跡般地消失了。
無論如何,謝謝您的幫助,這刺激了我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.