Button之常用事件
一、简介
1、button介绍
本文介绍了Buttonn的点击事件,触摸事件,获得焦点事件
接口分别为:OnClickListener,OnTouchListener,OnFocusChangeListener
这些事件并不是button才会有,别的控件也会有
2、button类结构
button继承的TextView,用法也几乎一样
二、方法
这个没啥说的,直接看实例吧
三、代码实例
效果图:
前
后
代码:
fry.Activity01
1 package fry; 2 3 import com.example.buttonDemo1.R; 4 5 import android.app.Activity; 6 import android.os.Bundle; 7 import android.view.MotionEvent; 8 import android.view.View; 9 import android.view.View.OnClickListener;10 import android.view.View.OnFocusChangeListener;11 import android.view.View.OnTouchListener;12 import android.widget.Button;13 14 public class Activity01 extends Activity implements OnClickListener,OnTouchListener,OnFocusChangeListener {15 private Button btn_one;16 private Button btn_two;17 int value=1;18 19 20 @Override21 protected void onCreate(Bundle savedInstanceState) {22 // TODO Auto-generated method stub23 super.onCreate(savedInstanceState);24 setContentView(R.layout.activity01);25 btn_one = (Button) findViewById(R.id.btn_one);26 btn_two = (Button) findViewById(R.id.btn_two);27 btn_one.setOnClickListener(this);28 btn_two.setOnClickListener(this);//触摸监听器29 btn_two.setOnTouchListener(this);30 btn_two.setOnFocusChangeListener(this);31 }32 33 @Override34 public void onClick(View v) {35 // TODO Auto-generated method stub36 Button btn = (Button) v;37 int width = getWindow().getWindowManager().getDefaultDisplay()38 .getWidth();39 /*40 * value等于1表示扩大41 * 等于-1表示缩小42 */43 if (btn.getWidth() < 100&&value==-1) {44 value=1;45 } else if (btn.getWidth() >= width&& value==1) {46 value=-1;47 }48 btn.setWidth(btn.getWidth()+(int)(btn.getWidth()*0.1*value));49 btn.setHeight(btn.getHeight()+(int)(btn.getHeight()*0.1*value));50 51 }52 53 @Override54 public boolean onTouch(View v, MotionEvent event) {55 // TODO Auto-generated method stub56 int action=event.getAction();//事件类型57 if(action==MotionEvent.ACTION_DOWN){ //按下58 btn_two.setBackgroundResource(R.drawable.button2);59 }else if(action==MotionEvent.ACTION_UP){ //松开60 btn_two.setBackgroundResource(R.drawable.button1);61 }62 //如果点击事件被处理,就传回true,否则false63 //也就是如果传true,事件被处理,onClick就不处理这个点击事件了64 return false;65 }66 67 @Override68 public void onFocusChange(View v, boolean hasFocus) {69 // TODO Auto-generated method stub70 if(hasFocus){ //获得焦点71 btn_two.setBackgroundResource(R.drawable.button2);72 }73 else if(!hasFocus){ //失去焦点74 btn_two.setBackgroundResource(R.drawable.button1);75 }76 }77 }
/buttonDemo1/res/layout/activity01.xml
1 26 7 13 14 20 21
四、易错点