本文介绍 android 中 button的 OnClickListener, OnTouchListener 事件。
运行结果截图:
1. activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/commonbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我的按钮一" />
<Button
android:id="@+id/imagebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button1"
android:gravity="center"
android:text="按钮" />
</LinearLayout>
2. MainActvity.java
package com.android.button1;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;
@SuppressLint("ShowToast")
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener {
private int value = 1; // 用于改变按钮的大小
private Button commonButton;
private Button imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commonButton = (Button) this.findViewById(R.id.commonbutton);
imageButton = (Button) this.findViewById(R.id.imagebutton);
commonButton.setOnClickListener(this);
imageButton.setOnClickListener(this);
imageButton.setOnTouchListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button) v;
if (value == 1
&& button.getWidth() == getWindowManager().getDefaultDisplay()
.getWidth()) {
value = -1;
} else if (value == -1 && button.getWidth() < 100) {
value = 1;
}
button.setWidth(button.getWidth() + (int) (button.getWidth() * 0.1)
* value);
button.setHeight(button.getHeight() + (int) (button.getWidth() * 0.1)
* value);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_UP) {
imageButton.setBackgroundResource(R.drawable.button2);
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
imageButton.setBackgroundResource(R.drawable.button3);
}
return false;
}
}
工程目录截图: