【问题标题】:Android/Java - setText to button within onbuttonclick cannot resolve methodAndroid/Java - setText 到 onbuttonclick 中的按钮无法解析方法
【发布时间】:2015-07-03 23:56:14
【问题描述】:

首先,让我以对 Android 开发完全陌生作为开场白。当我单击“此”按钮时,我试图简单地更改不同按钮上的文本。我可以使用 setVisibility() 更改可见性,所以我认为我正确引用了按钮 -​​ 但是当我尝试 setText() 时出现错误:“无法解析方法 '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);
}

【问题讨论】:

    标签: java android button settext


    【解决方案1】:

    你是在 Fragment 中还是在 Activity 中做呢?

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

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

    这就是我们添加元素的方式。如果您在布局中设置 Button 小部件,那么您需要引用此小部件。使用 ( ) 声明正确的类型和强制转换。

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

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

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

    【讨论】:

    • 完美解决方案。我尝试用您发布的正确代码替换我使用的错误“视图”代码,它显然工作正常。感谢您的回答,以及有关在听众之前引用小部件的建议。我会记住这一点。 [是的,这是在一个活动中]
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多