displaying a string on the textview when clicking a button in android

后端 未结 9 1967
情深已故
情深已故 2020-12-10 08:43

I\'m very new to Android development and just started to study.

What I\'m trying is to add a button and when that button is pressed a text \"my first project\" to ge

9条回答
  •  醉梦人生
    2020-12-10 09:04

    First create xml file as follows. Create one textview and a button:

    main.xml

    
    
    
      
    
      

    The first TextView is created by default. You can leave or remove it if you want. Next one is to create a button The next one is TextView where you want to display text.

    Now coming to the main activity code... package com.android.example.simple;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class SimpleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        final TextView textView=(TextView)findViewById(R.id.textView1);
        final Button button1 =  (Button)findViewById(R.id.mybutton);
    
        //Implement listener for your button so that when you click the 
        //button, android will listen to it.             
    
         button1.setOnClickListener(new View.OnClickListener() {             
            public void onClick(View v) {                 
            // Perform action on click 
                textView.setText("You clicked the button");
    
            }         });
        }
    }
    

提交回复
热议问题