您必须创建十六进制颜色代码数组并传递给自定义适配器类的主要活动
public class MainActivity extends Activity {
GridView gridView;
String[] gridColor ={
"#008B8B",
"#00FF00",
"#48D1CC",
"#556B2F",
"#696969",
"#6B8E23",
"#8FBC8F",
"#AFEEEE",
"#B8860B",
"#BDB76B",
"#D8BFD8",
"#DEB887",
"#FFFF00",
"#FFF0F5",
"#EE82EE",
"#DC143C",
"#C0C0C0"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Grid adapter = new Grid(MainActivity.this,gridColor);
gridView=(GridView)findViewById(R.id.grid_view);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Toast.makeText(MainActivity.this, "You Clicked On " +gridcolor[+ position], Toast.LENGTH_SHORT).show();
}
});
}
}
在自定义适配器代码将是这样的,其中颜色代码将被解析
public class Grid extends BaseAdapter {
private Context mContext;
private final String[] menu;
private final int[] Imageid;
private final String[] gridcolor;
public Grid(Context context,String[] menu,int[] Imageid,String[] gridcolor)
{
mContext=context;
this.gridcolor=gridcolor;
}
@Override
public int getCount() {
return gridcolor.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_layout, null);
grid.setBackgroundColor(Color.parseColor(gridcolor[i]));
} else
{
grid = view;
}
return grid;
}
}