我正在开发Android Wear应用程序,并且我有一个名为fitnessDebugToggle
的ToggleButton。它在我的清单中定义,可以通过findViewById
来引用。但是,只要我以任何其他方式访问它,我的应用程序就会崩溃。Android ToggleButton提供空对象参考
我目前正在平方米Wear设备(“Wear Square”)上调试我的应用程序,因此以下清单适用于平方设备。
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me.package.etc.MainActivity"
tools:deviceIds="wear_square">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:id="@+id/fitnessDebugText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="@string/fitnessDebugText"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ToggleButton
android:id="@+id/fitnessDebugToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textOff="@string/off"
android:textOn="@string/on"
android:layout_below="@+id/fitnessDebugText"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</ScrollView>
在我的MainActivity类别,我能写:
public class MainActivity extends Activity {
ToggleButton fitnessDebugToggle;
MainActivity mainActivity;
public MainActivity() {
mainActivity = this;
}
@Override
public void onCreate(Bundle bundle) {
// Show view
super.onCreate(bundle);
setContentView(R.layout.layout_main);
// Setup
fitnessDebugToggle = (ToggleButton) findViewById(R.id.fitnessDebugToggle);
}
}
然而正下方findViewById
电话,如果我把
fitnessDebugToggle.setTransformationMethod(null);
它的一部分崩溃堆栈跟踪为
产生的原因:显示java.lang.NullPointerException:尝试在上我增加了行空对象引用
调用虚拟方法“无效android.widget.ToggleButton.setTransformationMethod(android.text.method.TransformationMethod)”拨打setTransformationMethod
。
我已经看过Android studio “ Attempt to invoke virtual method on a null object reference”这个问题,但是它处理findViewById
调用中的NullPointerException,而不是进一步调用。在这个例子中我的包名也被改变了。
关于评论:
- 如果我注释掉
setTransformationMethod
并添加setOnCheckedChangeListener
电话,它具有类似的堆栈跟踪崩溃也是如此。 - 将ToggleButton的默认状态更改为false仍导致崩溃,原因与之前相同。
- 在我的布局XML中,将上下文更改为“.MainActivity”仍然以与之前相同的原因崩溃。
其实NPE应该已经在右= fitnessDebugToggle(切换按钮)findViewById(R.id.fitnessDebugToggle)发生;:作为
然后改变的onCreate methos当Null投射到ToggleButton时。您是否可以访问布局中的其他字段? – Naveen
@NaveenAechan不幸的是,没有。我注释掉setTransformationMethod并让它运行到setOnCheckedChangeListener。它也崩溃了,跟踪改为'void android.widget.ToggleButton.setOnCheckedChangeListener(android.widget.CompoundButton $ OnCheckedChangeListener'。 – Spotlight
检查您的布局名称是否正确。是activity_main.xml或layout_main.xml。如果是然后改变setContentView(R.layout.activity_main); –