事件三要素:事件源 事件 事件监听器
1.单击事件:
but.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
String str = et.getText().toString();
tv.setText(str);
}
});
2 按钮选项改变事件
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rb = (RadioButton) findViewById(checkedId);
String txt = rb.getText().toString();
tv.setText(txt);
}
});
3 下拉列表选项事件
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapt, View view,int position, long id) {
TextView tvv = (TextView) view;
String str = tvv.getText().toString();
tv.setText(str);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
4 日期和时间事件
tp.setOnTimeChangedListener(new OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
tv.setText(hourOfDay+":"+minute);
}
});
dp.init(2017,0, 25, new DatePicker.OnDateChangedListener(){
@Override
public void onDateChanged(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
tv.setText(""+year+monthOfYear+dayOfMonth);
}
});
5 焦点事件
et.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
TextView tvv = (TextView)v;
//hasFocues:是否获得焦点
if(hasFocus){
tvv.setText("");
}else{
tv.setText(tvv.getText().toString());
}
}
});
6 长按事件
//修改桌面背景需要配置权限
<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;
}
});
7 键盘事件
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;
}
});
8 触摸事件
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
tv.setText("("+event.getX()+","+event.getY()+")");
return false;
}
});