Android findViewById返回null(层次结构查看器显示与视图关联的无id)
我试图在谷歌地图上覆盖一个比例尺,但Android findViewById返回null(层次结构查看器显示与视图关联的无id),android,findviewbyid,Android,Findviewbyid,我试图在谷歌地图上覆盖一个比例尺,但findViewById()返回null并导致程序失败。我添加了两个textView来确定我的布局中的所有视图是否都被破坏,但是findviewbyd()为它们返回了有效的视图,也为google地图片段返回了有效的视图。我在Android设备监视器中使用了hierarchy viewer,并确定没有与ScaleBar视图关联的id protected void onCreate(Bundle savedInstanceState) { super.on
findViewById()
返回null并导致程序失败。我添加了两个textView来确定我的布局中的所有视图是否都被破坏,但是findviewbyd()
为它们返回了有效的视图,也为google地图片段返回了有效的视图。我在Android设备监视器中使用了hierarchy viewer,并确定没有与ScaleBar视图关联的id
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mTv1 = (TextView) findViewById(R.id.tv1);
mTv2 = (TextView) findViewById(R.id.tv2);
mScaleBar = (ScaleBar) findViewById(R.id.scale);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
我的布局文件“activity_maps.xml”:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1"
android:id="@+id/tv1"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<com.dbf.dirteditor.ScaleBar
android:id="@+id/scale"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text2"
android:id="@+id/tv2"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
我看这个太久了。。。我错过了什么蠢事?救命啊 您只调用1参数构造函数(忽略xml属性)。
因此,请按以下方式更改代码:
public ScaleBar(Context context) {
this(context,null);
}
public ScaleBar(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public ScaleBar(Context context, AttributeSet attrs, int defStyle) {
super(context,attrs,defStyle);
init_ScaleBar(context);
}
添加logcat消息重新检查XML是否与同一java文件关联谢谢!透过树林看不见森林。
public ScaleBar(Context context) {
this(context,null);
}
public ScaleBar(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public ScaleBar(Context context, AttributeSet attrs, int defStyle) {
super(context,attrs,defStyle);
init_ScaleBar(context);
}