Three methods of button click

the first method:

  1. property-method

xml:

android:onClick="clickDemo1"//alt+enter .

java:

@Override

public void onClick(View view) {}

2. The second method:

Anonymous inner class implements button monitoring

(1). First add the button and generate an id

(2). Define the object and instantiate the object

(3). Object. Method to add the anonymous inner class of the object

xml file

<Button

android: id="@+id/bt1" />

.java files

privite Button bt;

bt=findViewById(R.id.bt1);

bt.setOnClickListener(new V...{

@Override

public void onClick{ Toast.makeText(FirstActivity.this,"Demo1",Toast.LENGTH_SHORT).show();

}

});//alt+enter

  1. The third method:

The method that implements the interface:

(1) Add interface

(2) Add a listener

(3) Implement the interface

//step1 public class FirstActivity extends AppCompatActivity implements View.OnClickListener{ private Button bt;

void onCreate(){

bt=findViewById(R.id.bt1);

//step2, set the listener

bt.setOnClickListener(this);

}

//step3

@Override

public void onClick(View v) {

switch (v.getId()){

case R.id.bt1:

break;

}

Guess you like

Origin blog.csdn.net/2201_75449663/article/details/128961372