不難,所以不廢話,直接上代碼
/**
* 點(diǎn)擊item背景的gridView
* 至于為什么前綴為radio,因?yàn)檫@是單選的,你也可以改為多選的,原理一樣,有空我再寫
* Created by payne.
*/
public class RadioGridView extends GridView implements AdapterView.OnItemClickListener {
private int currentPosition = 0;
private OnRadioItemClickListener mListener;
private int mBgImageSelected;
private int mBgImageUnselected;
public RadioGridView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context, attrs);
}
//可以在xml文件直接設(shè)置item背景,是不是很方便
private void initView(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RadioGridView);
mBgImageSelected = typedArray.getResourceId(R.styleable.RadioGridView_item_selected,
R.drawable.item_selected);
mBgImageUnselected = typedArray.getResourceId(R.styleable.RadioGridView_item_unselected,
R.drawable.item_unselected);
typedArray.recycle();
setOnItemClickListener(this);
}
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//一個(gè)很小的邏輯,剛開始用的for循環(huán),感覺太low了,改為這種
int lastPosition = currentPosition;
currentPosition = position;
parent.getChildAt(lastPosition).setBackgroundResource(mBgImageUnselected);//未被選擇時(shí)的背景
view.setBackgroundResource(mBgImageSelected);//被選擇是的背景
if (mListener != null) {
mListener.onItemClick(getId(), position);
}
}
//設(shè)置高度,因?yàn)槲野l(fā)現(xiàn)高度變小了,不是正常高度
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
/**
* 設(shè)置item點(diǎn)擊監(jiān)聽器
*
* @param listener item點(diǎn)擊監(jiān)聽器
*/
public void setOnRadioItemClickListener(OnRadioItemClickListener listener) {
mListener = listener;
}
/**
* item點(diǎn)擊監(jiān)聽器
*/
public interface OnRadioItemClickListener {
/**
* @param gridViewId gridView id
* @param position item 位置
*/
void onItemClick(int gridViewId, int position);
}
}
attrs文件
<declare-styleable name="RadioGridView">
<attr format="reference" name="item_selected"/>
<attr format="reference" name="item_unselected"/>
</declare-styleable>
背景文件是單純的白色和紫紅色,就不上傳了
xml文件中的使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="20dp">
<com.payne.demo.RadioGridView
android:id="@+id/rgv"
android:background="#ffffff"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
app:item_selected="@drawable/item_selected"
app:item_unselected="@drawable/item_unselected"
tools:listitem="@layout/view_device_version_item"/>
</LinearLayout>
效果

Paste_Image.png