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!");
}
drdrdr
  • 2,788
  • 4
  • 17
  • 16

5 Answers5

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.

Pattabi Raman
  • 5,814
  • 10
  • 39
  • 60
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.

Tsunaze
  • 3,204
  • 7
  • 44
  • 81
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");}
}
bttcld
  • 67
  • 7
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);
}
Rod18
  • 1
  • 1
  • Please edit your answer and add some explanation because code-only answers are discouraged and may, sometimes, be deleted. – WebDevBooster Jan 27 '18 at 01: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")
    })
Imran Nawaz
  • 1
  • 1
  • 1