Button之常用事件
一、简介
1、button介绍
本文介绍了Buttonn的点击事件,触摸事件,获得焦点事件
接口分别为:OnClickListener,OnTouchListener,OnFocusChangeListener
这些事件并不是button才会有,别的控件也会有
2、button类结构
button继承的TextView,用法也几乎一样
二、方法
这个没啥说的,直接看实例吧
三、代码实例
效果图:
前
后
代码:
fry.Activity01
package fry; import com.example.buttonDemo1.R; import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button; public class Activity01 extends Activity implements OnClickListener,OnTouchListener,OnFocusChangeListener {
private Button btn_one;
private Button btn_two;
int value=1; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity01);
btn_one = (Button) findViewById(R.id.btn_one);
btn_two = (Button) findViewById(R.id.btn_two);
btn_one.setOnClickListener(this);
btn_two.setOnClickListener(this);//触摸监听器
btn_two.setOnTouchListener(this);
btn_two.setOnFocusChangeListener(this);
} @Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button btn = (Button) v;
int width = getWindow().getWindowManager().getDefaultDisplay()
.getWidth();
/*
* value等于1表示扩大
* 等于-1表示缩小
*/
if (btn.getWidth() < 100&&value==-1) {
value=1;
} else if (btn.getWidth() >= width&& value==1) {
value=-1;
}
btn.setWidth(btn.getWidth()+(int)(btn.getWidth()*0.1*value));
btn.setHeight(btn.getHeight()+(int)(btn.getHeight()*0.1*value)); } @Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int action=event.getAction();//事件类型
if(action==MotionEvent.ACTION_DOWN){//按下
btn_two.setBackgroundResource(R.drawable.button2);
}else if(action==MotionEvent.ACTION_UP){//松开
btn_two.setBackgroundResource(R.drawable.button1);
}
//如果点击事件被处理,就传回true,否则false
//也就是如果传true,事件被处理,onClick就不处理这个点击事件了
return false;
} @Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus){//获得焦点
btn_two.setBackgroundResource(R.drawable.button2);
}
else if(!hasFocus){//失去焦点
btn_two.setBackgroundResource(R.drawable.button1);
}
}
}
/buttonDemo1/res/layout/activity01.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮一"
></Button> <Button
android:id="@+id/btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button1"
></Button> </LinearLayout>
四、易错点