Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing TextView text on button click (Android)

Tags:

android

I am trying to change text of a textview on a button click. Below is the gist of my code but it doesnt seem to work. Am i doing something wrong. Thanks in Advance

//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!");
}
like image 535
drdrdr Avatar asked Sep 17 '11 11:09

drdrdr


2 Answers

  1. First you give onclick event for Button like (buttonClick).
  2. In java file just write below code.

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

Hope this will help you.

like image 99
Pattabi Raman Avatar answered Nov 15 '22 21:11

Pattabi Raman


Maybe you need to initialize the button. And if it doesn't work, just do it in java code :

Button btn = (Button) findViewById(YourId);
btn.setonClickListener(listener);

public onClickListener listener = new View.OnclickListener{
      onclick(View v){
      // do your thing
      }
}

Something like that, i don't remember without eclipse to correct me.

like image 43
Tsunaze Avatar answered Nov 15 '22 21:11

Tsunaze