If no. of TextView
s will stay 4, no matter what then don't use GridView
. Use LineareLayout
instead. Anyways your current approach will stop working if you add more TextView
s. At first glance your getView()
is faulty, you must do it like this:
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(convertView == null) {
Log.d("GRID_VIEW", "inflating");
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.grid_item, null);
} // <<<<-------------------
TextView text = (TextView) v.findViewById(R.id.gridItemText);
Log.d("GRID_VIEW", "creating view");
text.setText(mKeyInfo[position]);
switch(position) {
case 0:
text.setBackgroundColor(mContext.getResources().getColor(R.color.blue));
break;
case 1:
text.setBackgroundColor(mContext.getResources().getColor(R.color.yellow));
break;
case 2:
text.setBackgroundColor(mContext.getResources().getColor(R.color.green));
break;
case 3:
text.setBackgroundColor(mContext.getResources().getColor(R.color.red));
break;
default:
break;
}
return v;
}
Basically you must perform all state related operations every time getView()
is called due to View
recycling.
BTW why you are keeping reference to yourself in texts
array? Its very very bad practice. Why do you need this?
If you want to change the colors at later stage then you need to change your whole logic. You need to do something similar to this:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class MyAdapter extends BaseAdapter {
int[] colors = new int[4];
public MyAdapter(Context context) {
colors[0] = context.getResources().getColor(R.color.blue);
colors[1] = context.getResources().getColor(R.color.yellow);
colors[2] = context.getResources().getColor(R.color.green);
colors[3] = context.getResources().getColor(R.color.red);
}
@Override
public int getCount() {
return colors.length;
}
@Override
public Object getItem(int position) {
return colors[position];
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(convertView == null) {
Log.d("GRID_VIEW", "inflating");
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.grid_item, null);
} // <<<<-------------------
TextView text = (TextView) v.findViewById(R.id.gridItemText);
Log.d("GRID_VIEW", "creating view");
text.setText(mKeyInfo[position]);
text.setBackgroundColor(colors[position]);
return v;
}
// call this method to change colors at later stage
public void changeColor(int position, int color){
colors[position] = color;
notifyDataSetChanged();
}
// call this method to change text at later stage
public void changeText(int position, String text){
mKeyInfo[position] = text;
notifyDataSetChanged();
}
}