这里先用XML设置。
myselector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/img_pressed"/>
<item android:state_focused="true"
android:drawable="@drawable/img_focused"/>
<item android:drawable="@drawable/img_normal"/>
</selector>
将此文件放在res/drawable下面,并放入你想设置的图片背景文件,img_pressed.jpg,img_focused.jpg,img_mormal.jpg。
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton
android:id="@+id/imagebutton"
android:layout_gravity="center"
android:layout_marginTop="300px"
android:layout_width="200px"
android:layout_height="200px"
android:src="@drawable/myselector"
/>
</LinearLayout>
在Button下添加android:src指向myselector.xml就是采用其方法
MainActivity.java
package com.example.aimee.imagebuttontest;
import android.graphics.ColorMatrixColorFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton btn=(ImageButton) findViewById(R.id.imagebutton);
final float[] CLICKED=new float[]{
2,0,0,0,2,
0,2,0,0,2,
0,0,2,0,2,
0,0,0,1,0
};
final float[] CLICK_OVER=new float[]{
1,0,0,0,0,
0,1,0,0,0,
0,0,1,0,0,
0,0,0,1,0
};
// btn.setBackgroundResource(R.drawable.touch_up);
// btn.setOnTouchListener(new ImageButton.OnTouchListener(){
//
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// if(event.getAction()==MotionEvent.ACTION_DOWN){
// v.setBackgroundResource(R.drawable.touch_down);
// v.getBackground().setColorFilter(new ColorMatrixColorFilter(CLICKED));
// }
// else if(event.getAction()==MotionEvent.ACTION_UP){
// v.setBackgroundResource(R.drawable.touch_up);
// v.getBackground().setColorFilter(new ColorMatrixColorFilter(CLICK_OVER));
// v.setBackground(v.getBackground());
// }
// return false;
// }
// });
}
}
可用模拟器运行,可能遇到的问题,聚焦怎么实现,将鼠标悬浮在图片上并不能改变图片的状态,遇到这种情况,可以设置键盘聚焦。
可以在.android/avd/5.1_WVGA_API_26.avd下有一个config.ini的文件,讲其中的hw_dpad改为yes就可以了。
如果不用selector.xml设置,可以直接在java文件里设置,将代码中注释的部分打开,取消layout文件中的android:src=“@drawable/myselector”就行。