How to access individual items in Android GridView?
I'm trying to create a game with a 9x9 grid with GridView. Each item in the grid is a TextView. I am able to set the initial values of each item in the grid within the getView() method to "0", however I want to change the value of each grid individually after this but have been unable to do so.
I tried adding an update() function in my extended GridAdapter class that takes a position and a number to update at that position but this doesnt seem to be working.
public void update(int position, int number) {
TextView cell;
cell = (TextView) getItem(position);
if (cell != null)
{
cell.setText(Integer.toString(number));
}
}
Doe anyone know how this can be achieved?
Here's the whole GridAdapter class in case require,
public class SudokuGridAdapter extends BaseAdapter {
private Context myContext;
private TextView[] myCells;
public SudokuGridAdapter(Context c) {
myContext = c;
myCells = new TextView[9*9];
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 9*9;
}
@Override
public Object getItem(int position) {
return myCells[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView cell;
if (myCells[position] == null)
{
cell = myCells[position] = new TextView(myContext);
cell.setText("0");
}
else
{
cell = myCells[position];
}
return cell;
}
public void update(int position, int number) {
TextView cell;
cell = (TextView) getItem(position);
if (cell != 开发者_开发技巧null)
{
cell.setText(Integer.toString(number));
}
}
}
Try to put "notifyDataSetChanged();" line at the end of your "update" method.
P.S. It would be better if you replace "myCells" array type (and view rendering accordingly) to another one, which more close to your domain model.
精彩评论