11

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? Commented Sep 17, 2011 at 11:36
  • From where is wrongAns(View v) function called? Please provide more details. Commented Sep 17, 2011 at 11:37
  • outside of public class applicationName extends Activity. 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 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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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");} } 

Comments

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 Comment

Please edit your answer and add some explanation because code-only answers are discouraged and may, sometimes, be deleted.
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") }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.