【问题标题】:How to set text of android button in onCreate Method?如何在 onCreate 方法中设置 android 按钮的文本?
【发布时间】:2021-04-05 03:06:43
【问题描述】:

我想在 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" />

这是一个例外:

引起:java.lang.NullPointerException:尝试调用虚拟 方法 'void android.widget.Button.setText(java.lang.CharSequence)' on 空对象引用

我知道我可以在 XML 中设置按钮的文本,但我想通过 sharedpreferences 在应用程序启动时设置文本,但如果我什至不能通过调用它来设置一个简单的字符串,它就行不通简单的方法。

【问题讨论】:

  • 你先打电话给setContentView(your_layout.xml)了吗?否则,您的活动不会有任何视图,findViewById 找不到任何东西。
  • 是的,但该按钮不在 activity_main.xml 中。它在 fragment_recording.xml 中。

标签: java android button oncreate


【解决方案1】:

要查找 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");

    }

【讨论】:

  • 这个方法要放在哪里?
  • 片段中的@OSbOoL
  • 非常感谢。这就是我要找的。​​span>
【解决方案2】:

您最好分享整个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")
    }

【讨论】:

  • onCreate 没问题,Button 在另一个片段中,而不是在 activity_main.xml 中。这可能是错误吗?但是我怎样才能访问我的按钮呢?如果我输入“R.id”。然后我的按钮正在显示....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多