10

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!");
}
8
  • What is happening when you click the button?
    – Aleks G
    Commented Sep 17, 2011 at 11:36
  • From where is wrongAns(View v) function called? Please provide more details.
    – Shafi
    Commented Sep 17, 2011 at 11:37
  • outside of public class applicationName extends Activity.
    – drdrdr
    Commented Sep 17, 2011 at 11:39
  • code, seems fine, can you post the crash log? Commented Sep 17, 2011 at 11:44
  • your code is working just perfect
    – Abhi
    Commented Sep 17, 2011 at 11:50

5 Answers 5

23
  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.

1

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.

0

In a simple view with the background a textbox and a button you need to use

public void OnMyButtonClick (View v)
{
    TextView tv = (TextView) v.getRootView().findViewById(R.id.textVal);
    if (tv != null)
      {tv.setText("Hallo");}
}
0

Use setContentView, please check What is setContentView(R.layout.main)?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mStatusTextView = (TextView) this.findViewById(R.id.status_text_view);
}
1
  • Please edit your answer and add some explanation because code-only answers are discouraged and may, sometimes, be deleted. Commented Jan 27, 2018 at 1:16
0

In Kotlin To add an OnClickListener to a Button to change the Text(value) of a TextView You have to write the following code in the onCreate method of MainActivity

    var textView = findViewById<TextView>(R.id.text)        
    var button = findViewById<Button>(R.id.button)
    button.setOnClickListener(View.OnClickListener {
        textView.setText("Imran Khan")
    })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.