-1
我想爲我打造一個基本顏色選擇器,其中顯示了供用戶選擇的10種顏色的列表。Android GridView突出顯示項目爲選中
我決定使用GridView來保存在我的情況和ImageView與ShapeDrawables的顏色列表(很想聽到更好的解決方案)。
我在計算如何突出顯示單擊時選中的項目以及如何只同時選擇一個項目(單選模式)時遇到問題。
任何想法如何?
CODE:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.mygrid);
gridView.setAdapter(new MyAdapter(this));
gridView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Selected color
int color = (int) adapterView.getItemAtPosition(i);
// Selected view
ImageView bla = (ImageView) view;
}
public class MyAdapter extends BaseAdapter {
private final Context c;
public MyAdapter(Context c) {
this.c = c;
}
@Override
public int getCount() {
return colors.length;
}
@Override
public Object getItem(int i) {
return colors[i];
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ImageView ivColor;
if (view == null) {
LinearLayout.LayoutParams lpParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
lpParams.gravity = Gravity.CENTER;
ivColor = new ImageView(c);
ivColor.setLayoutParams(lpParams);
} else {
ivColor = (ImageView) view;
}
ShapeDrawable shape = new ShapeDrawable(new OvalShape());
shape.getPaint().setColor(colors[i]);
shape.setIntrinsicWidth(180);
shape.setIntrinsicHeight(180);
ivColor.setImageDrawable(shape);
return ivColor;
}
private int[] colors = {
Color.BLUE, Color.BLACK, Color.CYAN, Color.GREEN, Color.YELLOW, Color.DKGRAY, Color.MAGENTA, Color.RED
};
}
}
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"
tools:context=".MainActivity">
<GridView
android:id="@+id/mygrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:columnWidth="64dp"
android:horizontalSpacing="8dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="8dp" />
</LinearLayout>