先看一下效果吧
就是简单new了两个imageview,然后给两个imageview添加焦点,实时返回焦点所处的imageviw
简单的封装
因为我的按钮都是需要通过云端自定义的,所以都是在代码里面new出来的
ImageViewClick.java
public class ImageViewClick {
ImageFocus imageFocus;
//焦点
public static void Image(ImageView[] imageViews, Context context, ImageFocus imageFocus) {
for(ImageView s : imageViews) {
//初始化一下样式
s.setBackgroundColor(0x80CFCFCF);
s.setFocusable(true);
s.isFocusableInTouchMode();
//焦点
s.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.e("Home230115-t","找到焦点");
ImageViewStyle(hasFocus,s,context,imageFocus);
}
});
}
}
private static void ImageViewStyle(Boolean tf, ImageView imageView,Context context,ImageFocus imageFocus) {
if (tf) {
Log.e("Home230115-t",tf+"");
imageView.setBackground(context.getResources().getDrawable(R.drawable.imageview_border_show));
imageView.setPadding(10,10,10,10);
imageFocus.ChooseImage(imageView);
} else {
Log.e("Home230115-f",tf+"");
imageView.setBackground(context.getResources().getDrawable(R.drawable.imageview_border_hint));
imageView.setPadding(10,10,10,10);
}
}
}
这个是接口
拿到焦点就回调,告诉ui我当前是在哪个image上
ImageFocus.java
public interface ImageFocus {
void ChooseImage(ImageView imageView);
}
使用的话就很简单
ll_tab是我在xml画好的布局,用来限制这些imageview的位置
private void setTab(){
ImageView iv_Film = new ImageView(MainActivity.this);
iv_Film.setImageDrawable(getResources().getDrawable((R.drawable.ic_tab_film_n)));
ll_tab.addView(iv_Film);
ImageView iv_Catering = new ImageView(MainActivity.this);
iv_Catering.setImageDrawable(getResources().getDrawable((R.drawable.ic_tab_film_n)));
ll_tab.addView(iv_Catering);
ImageView imageViews[] = {iv_Film,iv_Catering};
ImageViewClick.Image(imageViews, MainActivity.this, new ImageFocus() {
@Override
public void ChooseImage(ImageView imageView) {
//imageView.setImageDrawable(getResources().getDrawable((R.drawable.logo)));
}
});
}
最后有两个选中和未选中的样式
imageview_border_hint.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="0px" />
<stroke
android:width="0px"
android:color="@color/teal_200" />
<solid android:color="@android:color/transparent" />
<!-- <padding-->
<!-- android:bottom="10dp"-->
<!-- android:left="10dp"-->
<!-- android:right="10dp"-->
<!-- android:top="10dp" />-->
</shape>
imageview_border_show.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<stroke
android:width="2dp"
android:color="#ffffff" />
<solid android:color="#00000000" />
<!-- <size-->
<!-- android:height="260dp"-->
<!-- android:width="155dp"/>-->
<!-- <padding-->
<!-- android:bottom="20dp"-->
<!-- android:left="20dp"-->
<!-- android:right="20dp"-->
<!-- android:top="20dp" />-->
</shape>