我正在开发一个 Android Wear 应用程序,我有一个名为
fitnessDebugToggle
的 ToggleButton。它在我的清单中定义,可以通过 findViewById
引用。但是,每当我以其他方式访问它时,我的应用程序都会崩溃。
我目前正在方形 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:尝试在空对象引用上调用虚拟方法“void android.widget.ToggleButton.setTransformationMethod(android.text.method.TransformationMethod)”
在该行我添加了
setTransformationMethod
调用。
我已经查看了问题 Android studio“尝试在空对象引用上调用虚拟方法”,但是它处理的是
findViewById
调用上的 NullPointerException,而不是进一步调用。在这个例子中我的包名称也被更改了。
关于评论:
setTransformationMethod
并添加 setOnCheckedChangeListener
调用,它也会崩溃并出现类似的堆栈跟踪。您只能在一种情况下使用 null,例如 try if else
if(checked){
button.setTransformationMethod(null);
}else {
button.setTransformationMethod(new PasswordTransformationMethod());
}
如果您重命名 xml 文件,请尝试 android studio 的此选项:
File -> Invalidate Catches/Restart
然后甚至出现问题,更改 xml 中的 ToggleButton id 并检查 java 文件是否给出错误?如果是,则 id 已在 R.java 中完美集成和更新。
然后将 onCreate 方法更改为:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
}
我遇到了
findViewById
为布局的所有元素返回 null 的问题。最后只需要重建项目就解决了。
非常烦人的问题。