Android/Java - onbuttonclick 中的 setText to button 无法解析方法

Android/Java - setText to button within onbuttonclick cannot resolve method

首先让我以对 Android 开发完全陌生作为序言。当我单击 "this" 按钮时,我试图简单地更改不同按钮上的文本。我可以使用 setVisibility() 更改可见性,所以我认为我正确地引用了按钮 -​​ 但是当我尝试 setText() 时,我收到错误:"Cannot resolve method 'setText(Java.Lang.String)'"

为什么它允许我更改可见性而不是文本?我需要做什么来解决这个问题?

这是我试图更改文本的其中一个按钮的 XML 的一部分:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/songbutton4"
    android:layout_below="@+id/button4"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/button4"
    android:layout_alignEnd="@+id/button4"
    android:visibility="invisible" />

这是 onclick 事件的代码:

public void onbutton1click(View v){
 //on click turn the 4 buttons invisible, and show the other 5
    View b1 = findViewById(R.id.button1);
    b1.setVisibility(View.INVISIBLE);
    View b2 = findViewById(R.id.button2);
    b2.setVisibility(View.INVISIBLE);
    View b3 = findViewById(R.id.button3);
    b3.setVisibility(View.INVISIBLE);
    View b4 = findViewById(R.id.button4);
    b4.setVisibility(View.INVISIBLE);
    View b5 = findViewById(R.id.button5);
    b5.setVisibility(View.INVISIBLE);

    View sb1 = findViewById(R.id.songbutton1);
    sb1.setVisibility(View.VISIBLE);
    sb1.setText("hello");  // THIS IS WHERE THE ERROR OCCURS
    View sb2 = findViewById(R.id.songbutton2);
    sb2.setVisibility(View.VISIBLE);
    View sb3 = findViewById(R.id.songbutton3);
    sb3.setVisibility(View.VISIBLE);
    View sb4 = findViewById(R.id.songbutton4);
    sb4.setVisibility(View.VISIBLE);
}

您是在 Fragment 中还是在 Activity 中进行?

无论如何,你应该这样做:

Button sb1 = (Button) findViewById(R.id.songbutton1);

这就是我们添加元素的方式。如果您在布局中设置 Button 小部件,则您需要以这种方式引用该小部件。使用 ( ).

声明正确的类型和转换

如果您是在 Fragment 中而不是在 Activity 中进行操作,您还需要将其绑定到正确的视图。

Button sb1 = (Button) v.findViewById(R.id.songbutton1);

还有建议 - 不要在侦听器中获取对视图(小部件)的引用。在听众之前做。

首先将按钮分配给一个变量,即:Button btnSong = (Button) findViewById(R.id.songbutton4);
然后通过 btSong.setOnClickListener(); 方法为按钮设置一个 onclick 侦听器,这将要求您在其中声明一个新的 onClickListener将创建按钮和方法,您可以在其中将上述代码放在该方法下。或者添加一个 XML 属性,将按钮直接指向方法。