【发布时间】:2014-01-09 23:11:53
【问题描述】:
我正在按照书中的示例进行操作,但我不明白为什么 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();
}
【问题讨论】:
-
错误说明了什么?
-
没有罗盘视图的
res/layout-{modifier}/main.xml的任何资源变体? -
尝试不使用“this”。只有 CompassView cv = (CompassView) findViewById(R.id.compassView1);
-
@El_Mochiq 这段代码不会出错,但如果我尝试使用 cv 我会得到一个空指针异常
-
您能否发布您的
CompassView构造函数代码 - 可能属性未正确传递给超类 ctor。
标签: android view findviewbyid