BUTTON 按钮焦点变化
在res / drawable- hdpi文件中先存储 3张图片:button1,button2,button3,作为按钮的背景图片。效果如下,每次点击图标会使图标变大,直到抵达窗体大小,继续点击就会不断变小至恢复原形:
完成步骤一:在layout文件夹中的activity_main.xml中完成代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/commonbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="真" >
</Button>
<Button
android:id="@+id/imagebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button1"
android:gravity="center"
android:text="假" >
</Button>
</LinearLayout>
package com.example.buttontest;
import android.os.Bundle;
import android.app.Activity;
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;
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener, OnFocusChangeListener, OnKeyListener {
private int value = 1; //改变按钮大小
private Button commonButton;
private Button imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (Button) this.findViewById(R.id.imagebutton);
commonButton = (Button) this.findViewById(R.id.commonbutton);
commonButton.setOnClickListener(this);//注册几个事件
imageButton.setOnClickListener(this);
imageButton.setOnTouchListener(this);
imageButton.setOnFocusChangeListener(this);
imageButton.setOnKeyListener(this);
}
public void onClick(View v) {//当发生点击事件
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.getHeight()*0.1)*value);
}
public boolean onKey(View v,int keyCode,KeyEvent event){//定义健事件
if(KeyEvent.ACTION_DOWN == event.getAction()){ //按下时,得到button3的背景图片
v.setBackgroundResource(R.drawable.button3);
}else if(Ke