事件
三要素:
事件源
事件
事件监听器
单击事件
but.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String str = et.getText().toString();
tv.setText(str);
}});
按钮选项改变事件
rg.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup group, int checkedId) {
rb=(RadioButton) findViewById(checkedId);
String txt=rb.getText().toString();
tv.setText(txt);
}}
);
下拉列表选项事件
sp.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View view,
int arg2, long arg3) {
TextView tvv=(TextView)view;
String str=tvv.getText().toString();
tv.setText(str);
}
public void onNothingSelected(AdapterView<?> arg0) {
}} );
日期和时间事件
tp.setOnTimeChangedListener(new OnTimeChangedListener(){
public void onTimeChanged(TimePicker arg0, int hourOfDay, int minute) {
tv.setText(hourOfDay+" "+":"+minute);
}});
dp.init(2017, 0, 25, new DatePicker.OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
tv.setText(""+year+monthOfYear+dayOfMonth);
}
});
焦点事件
et.setOnFocusChangeListener(new OnFocusChangeListener(){
public void onFocusChange(View v, boolean hasFoces) {
TextView tvv=(TextView) v;
//hasFocues:是否获得焦点
if(hasFoces){
tvv.setText("");
}else{
tv.setText(tvv.getText().toString());
}
}});
长按事件
//修改桌面背景需要配置权限
<uses-permission android:name="android.permission.SET_WALLPAPER" />
img.setOnLongClickListener(new OnLongClickListener() {
//两个事件:long--> click
// false --> 不去运行click
// true --> 去运行click
@Override
public boolean onLongClick(View v) {
try {
Day07.this.clearWallpaper();
Day07.this.setWallpaper(
Day07.this.getResources().
openRawResource(R.drawable.a));
tv.setText("设置成功");
} catch (IOException e) {
tv.setText("设置失败");
e.printStackTrace();
}
return true;
}
});
键盘事件
et.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()==KeyEvent.ACTION_UP){
String str = et.getText().toString();
if(str.matches("\w+[@]\w+[.]\w+")){
iv.setImageResource(R.drawable.a);
}else{
iv.setImageResource(R.drawable.icon);
}
}
return false;
}
});
触摸事件
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
tv.setText("("+event.getX()+","+event.getY()+")");
return false;
}
});