简体   繁体   English

如何在 onCreate 方法中设置 android 按钮的文本?

[英]How to set text of android button in onCreate Method?

I want to set the text of my button in onCreate Method, but it doesn't work.我想在 onCreate 方法中设置按钮的文本,但它不起作用。

Code in MainActivity-Class: MainActivity 类中的代码:

Button button;

Code in onCreate: onCreate 中的代码:

button = findViewById(R.id.button);
    button.setText("test");

Butto in xml: 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" />

Here's the Exception:这是例外:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference

I know that I can set the text of button in XML, but I want to set the text at app start via sharedpreferences, but it won't work if I can't even set a simple string onto it by calling this easy way.我知道我可以在 XML 中设置按钮的文本,但我想通过 sharedpreferences 在应用程序启动时设置文本,但如果我什至不能通过调用这种简单的方法在其上设置一个简单的字符串,它就行不通。

You better share the whole onCreate() code in order to get help.您最好共享整个onCreate()代码以获得帮助。

By now, I could assume you don't call setContentView(R.layout.your_layout_with_button) in onCreate() method before accessing button by calling findViewById(R.id.button) .到目前为止,我可以假设您在通过调用findViewById(R.id.button)访问按钮之前没有在onCreate()方法中调用setContentView(R.layout.your_layout_with_button) ) 。

Whole code inside onCreate() will be looking smth like this: 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")
    }

To find id fragment you need view reference.要查找 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");

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM