问题描述
我想在 onCreate 方法中设置按钮的文本,但不起作用。
MainActivity-Class 中的代码:
Button button;
onCreate 中的代码:
button = findViewById(R.id.button);
button.setText("test");
xml 中的按钮:
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:alpha="0.5"
android:background="@color/design_default_color_secondary_variant"
android:onClick="checkPermissions"
android:textSize="30sp" />
这里是例外:
Caused by: java.lang.NullPointerException: Attempt to invoke 方法 'void android.widget.Button.setText(java.lang.CharSequence)' on 空对象引用
我知道我可以在 XML 中设置按钮的文本,但是我想通过共享首选项在应用程序启动时设置文本,但是如果我什至无法通过调用它来设置一个简单的字符串,它就无法工作简单的方法。
解决方法
您最好共享整个 onCreate()
代码以获得帮助。
现在,我可以假设你不会打电话
在通过调用 setContentView(R.layout.your_layout_with_button)
访问按钮之前,onCreate()
方法中的 findViewById(R.id.button)
。
onCreate()
中的整个代码看起来像这样:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.your_layout_with_button)
val button = findViewById(R.id.button)
button.setText("test")
}
,
要查找 id 片段,您需要查看引用。
@Override
public void onViewCreated(@NonNull View view,@Nullable Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
Button button= view.findViewById(R.id.button);
button.setText("text");
}