how to add button click event in android studio

前端 未结 14 1262
面向向阳花
面向向阳花 2020-12-24 11:04

So I have done some research, and after defining you button as an object by the code

private Button buttonname;
buttonname = (Button) findViewById(R.id.butto         


        
相关标签:
14条回答
  • 2020-12-24 11:32
    package com.mani.smsdetect;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class MainActivity extends Activity implements View.OnClickListener {
    
        //Declaration Button
        Button btnClickMe;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //Intialization Button
    
            btnClickMe = (Button) findViewById(R.id.btnClickMe);
    
            btnClickMe.setOnClickListener(MainActivity.this);
            //Here MainActivity.this is a Current Class Reference (context)
        }
    
        @Override
        public void onClick(View v) {
    
            //Your Logic
        }
    }
    
    0 讨论(0)
  • 2020-12-24 11:33
    public class MainActivity extends AppCompatActivity implements View.OnClickListener
    

    Whenever you use (this) on click events, your main activity has to implement ocClickListener. Android Studio does it for you, press alt+enter on the 'this' word.

    0 讨论(0)
提交回复
热议问题