2010-06-13 53 views
0

我想用GridView創建一個9x9網格的遊戲。網格中的每個項目都是一個TextView。 我可以將getView()方法中的網格中的每個項目的初始值設置爲「0」,但是我想在這之後單獨更改每個網格的值,但無法這樣做。如何訪問Android GridView中的單個項目?

我試着在我的擴展GridAdapter類中添加一個update()函數,該函數需要一個位置和一個數字來更新該位置,但這似乎不起作用。

public void update(int position, int number) { 
TextView cell; 
cell = (TextView) getItem(position); 
if (cell != null) 
{ 
    cell.setText(Integer.toString(number)); 
} 
} 

Doe有人知道這可以實現嗎?

這裏是整個GridAdapter類在需要的情況下,

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)); 
    } 
} 

} 
+0

嘿米試圖做類似的事情。但我在更新函數中獲取單元格爲空。無法查看。你能幫我嗎? – 2012-10-25 20:35:05

回答

0

嘗試把 「notifyDataSetChanged();」在你的「更新」方法的最後。

P.S.如果將「myCells」數組類型(並相應地查看渲染)替換爲更接近域模型的另一個,會更好。

+0

謝謝你會嘗試。 沒有完全得到第二點。你的意思是說用其他視​​圖類型替換TextView數組嗎? – 2010-06-14 09:01:54