本Android教程解释了Android的一个非常重要的部分,即事件监听器(Event Listeners)。
Android侦听器用于捕获事件。例如,当用户通过单击按钮与Android系统进行交互时,侦听器将提示基础活动执行与按钮单击相关的任务。
因此,每当我们希望Android系统执行任务时(发生事件时),侦听器就会起作用。在Android系统中,侦听器有20多个,但更频繁一些。在本Android教程中,我们将仅坚持基础知识。
以下是最常用的基本侦听器:
OnClickListener
OnTouchListener
OnDateSetListener
如果要在单击时执行任务,则使用OnClickListener。
示例:单击按钮时,toast将显示点击次数。
这是此示例的代码:
a)在onCreate方法之外全局声明一个变量:
//Declaring
the variable to count the number of clicks
int count = 0;
b)在onCreate方法中实现以下内容。其中我们在Button上设置一个OnClickListener:
the Button and Type Casting it.
Button btn1 = (Button) findViewById(R.
id
.button1);
//Setting
OnClickListener on btn1
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View
v
) {
//Executing
the following code on the click
//Incrementing
the variable count by 1 on the click of the button
count++;
//Displaying
the count using a Toast Toast.makeText(MainActivity.this,
"The button has been clicked "
+ count +
" times"
,Toast.LENGTH_SHORT).show();
}
});
OnTouchListener用于捕获触摸事件并执行与之关联的任务。
示例:在触摸按钮时,将显示一个吐司及其计数(发生触摸事件的次数)。
这是上面示例的代码:
b)在onCreate方法中实现以下内容。其中我们在按钮上设置一个OnTouchListener:
OnTouchListener on btn1
btn1.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View
, MotionEvent event) {
the variable count by 1 on every Touch
Toast.makeText(MainActivity.this,
"The button has been touched "
return
false
;
它用于从DatePicker小部件中获取选定的日期。
示例:在按钮上单击,将显示一个DatePickerDialog,我们可以从中选择一个日期。做出选择后,单击"完成"按钮,将显示带有所选日期的祝酒词。
a button and the DatePickerDialog
private Button btnDatePicker;
DatePickerDialog _date;
在onCreate方法中实现以下内容。其中我们在按钮上设置一个OnClickListener:
//Typecasting
the Button
btnDatePicker = (Button) findViewById(R.
an OnclickListener on the Button
btnDatePicker.setOnClickListener(new OnClickListener() {
//Creating
an object of DatePickerDialog incontext of the Mainactivity
//dateCallback
is called
which
defined below
_date = new DatePickerDialog(MainActivity.this, dateCallback, 2012, 10, 12);
//Showing
the DatePickerDialog
_date.show();
OnDateSetListener on the DatePickerDialog
private DatePickerDialog.OnDateSetListener dateCallback = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
a Toast with the
date
selected
"The date is : "
+ dayOfMonth+
"/"
+ ++monthOfYear +
+ year, Toast.LENGTH_LONG).show();
};
原文链接:https://codingdict.com/