[英]Android - findViewById returns null
我正在看一本書中的示例,但我不明白為什么findViewById返回null。
這是我的活動:
package it.mt.compass;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class CompassActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CompassView cv = (CompassView)this.findViewById(R.id.compassView1);
// this crashes the application
//cv.setBearing(45);
// some debug code
Toast test_result;
if(cv == null) {
test_result = Toast.makeText(this, "1", Toast.LENGTH_SHORT);
test_result.show();
}
else {
test_result = Toast.makeText(this, "0", Toast.LENGTH_SHORT);
test_result.show();
}
// it shows 1
}
}
這是res / layout / main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<it.mt.compass.CompassView
android:id="@+id/compassView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
項目已經運氣好(如其他類似主題所述;“清理”有什么用?),但運氣不好。
提前謝謝了。 米爾科
根據要求,構造函數的代碼為:
// Constructors
public CompassView(Context context) {
super(context);
initCompassView();
}
public CompassView(Context context, AttributeSet attrs) {
super(context);
initCompassView();
}
public CompassView(Context context, AttributeSet ats, int defaultStyle) {
super(context);
initCompassView();
}
那是正確的版本(問題是我沒有正確地將參數傳遞給超類構造函數):
// Constructors
public CompassView(Context context) {
super(context);
initCompassView();
}
public CompassView(Context context, AttributeSet attrs) {
super(context, attrs);
initCompassView();
}
public CompassView(Context context, AttributeSet ats, int defaultStyle) {
super(context, ats, defaultStyle);
initCompassView();
}
CompassView
構造函數實現不正確。 您沒有將屬性傳遞給超類,因此id
丟失了。
在這里更改超類構造函數的調用
public CompassView(Context context, AttributeSet attrs) {
super(context);
super(context, attrs);
和
public CompassView(Context context, AttributeSet ats, int defaultStyle) {
super(context);
super(context, attrs, defaultStyle);
如果超類的ctor接受三個args。 否則,只需使用super(context, attrs)
。 哦,從ats
重命名arg名稱,即使名稱無關緊要。
在日食中:
這將清除生成的舊R類。
我會嘗試完全關閉Eclipse,然后再次將其打開。 我已經看到像這樣的事情發生了一些非常奇怪的事情。 您可以嘗試執行此操作的另一種方法是,僅添加一個“ textView”,然后嘗試對它執行findById,然后查看它是否返回null。 您可能加載了錯誤的xml視圖。
即:您正在從一個目錄加載布局,但實際上是在另一個具有相同名稱的目錄中加載另一個視圖...
添加import it.mt.compass.R;
然后嘗試其他視圖,例如Image或TextView
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.