Write blog is to record their own learning, can learn and consolidate back, let's look at 3 key listener method it
One
Way to use anonymous inner classes of registered listeners, when you click the button will execute onClick () method listener, where new View.OnClickListener () for anonymous inner classes, event handling is added in onClick () method
code show as below:
edit = findViewById(R.id.et_edit);
send = findViewById(R.id.bt_send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String et = edit.getText().toString().trim();
Toast.makeText(MainActivity.this,et,Toast.LENGTH_SHORT).show();
}
});
Two
You can also register listeners use interface mode, the current class implements OnClickListener interface, the interface must add the onClick () method, add a handle events onClick () method
Basic Code
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public EditText edit;
public Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = findViewById(R.id.et_edit);
send = findViewById(R.id.bt_send);
}
@Override
public void onClick(View v) {
String et = edit.getText().toString().trim();
Toast.makeText(this,et,Toast.LENGTH_SHORT).show();
}
}
Three
Add in the layout file android: onClick property to implement monitoring, the value of the control method name behind the property, you need to write the method attribute value method name in the java file. As shown in the code, I define android: onClick = "send", then in the method of the current class I write send (View view)
Layout file
<Button
android:id="@+id/bt_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="send"
android:text="发送" />
java file
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = findViewById(R.id.et_edit);
}
public void send(View view) {
String et = edit.getText().toString().trim();
Toast.makeText(this,et,Toast.LENGTH_SHORT).show();
}
. . . . . Current understanding is that these three ways to listen