我正在开发一个 Android Wear 应用,并且有一个名为 fitnessDebugToggle
的 ToggleButton。它在我的 list 中定义,可以通过 findViewById
引用。但是,每当我以其他方式访问它时,我的应用程序就会崩溃。
我目前正在方形 Wear 设备(“Wear Square”)上调试我的应用,因此以下 list 适用于方形设备。
<?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);
它因部分堆栈跟踪而崩溃
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ToggleButton.setTransformationMethod(android.text.method.TransformationMethod)' on a null object reference
在该行我添加了 setTransformationMethod
调用。
我看过问题Android studio “ Attempt to invoke virtual method on a null object reference”但是,它处理的是 findViewById
调用上的 NullPointerException,而不是进一步调用时的 NullPointerException。在这个例子中我的包名称也被更改了。
关于评论:
- 如果我注释掉
setTransformationMethod
并添加setOnCheckedChangeListener
调用,它也会崩溃并出现类似的堆栈跟踪。 - 将 ToggleButton 的默认状态更改为 false 仍然会导致崩溃,原因与之前相同。
- 在我的布局 XML 中,将上下文更改为“.MainActivity”仍然会崩溃,原因与以前相同。
最佳答案
您只能在一种情况下使用 null,例如 try if else
if(checked){
button.setTransformationMethod(null);
}else {
button.setTransformationMethod(new PasswordTransformationMethod());
}
关于java - Android ToggleButton 提供 null 对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532928/