单击按钮更改TextView文本(Android)

drd*_*rdr 7 android

我试图在按钮单击时更改textview的文本.下面是我的代码的要点,但它似乎没有工作.难道我做错了什么.提前致谢

//xml
<TextView android:id="@+id/textView2" android:text="blah blah blah"></TextView>
<Button android:text="Wrong answer." android:onClick="wrongAns" android:clickable="true"></Button>

//code
TextView theCorrectAnsTextView = (TextView)findViewById(R.id.textView2);

public void wrongAns(View v) 
{   
  theCorrectAnsTextView.setText("TextView text has changed!");
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 17

  1. 首先,您为Button(onClickClick)提供onclick事件.
  2. 在java文件中只需编写下面的代码.

    public void buttonClick(View v)
    {
    TextView tv = (TextView)findViewById(R.id.textView1);
    tv.setText("Welcome to android");
    }
    
    Run Code Online (Sandbox Code Playgroud)

希望这会帮助你.