Search code examples
androidlistenersettext

Setting text and adding listener in android


I have made an Android blank project, then in the activity.xml page I added buttons and TextViews to the panel.

I want a code in the activity.java that changes the TextView in the activity if a button is pressed, how do I do that?

What I found out is the id in the .java file would be the following:

  • R.id.TextView1 for TextView
  • R.id.Button01 for Button

I want when I press the button the text is set to "hi", can someone help me with this please? I am new to android and google search have failed me or use some weird way I don't understand. I need the basics.


Solution

  • just replace this oncreate with yours and your code will work.

    TextView textView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity);
    
            Button button = (Button) findViewById(R.id.Button01); // get the button object
            textView = (TextView) findViewById(R.id.TextView1); // get the textView object
    
            button.setOnClickListener( new View.OnClickListener() { // set the click listener for the button
                @Override
                public void onClick(View view) {
                    textView.setText("hi"); 
                }
            });
        }