1
我想要編寫一個簡單的Boggle應用程序。有一個「洗牌板」按鈕,應該洗牌所有的立方體,並顯示新的板。GridView沒有被更新
的問題是:即使我更新LetterAdapter
(內LetterAdapter#shuffle
,我叫notifyDataSetChanged
)和使用refreshDrawableState()
任意組合,invalidate()
,invalidateViews()
內onClick
我不能得到的視圖進行更新。我能找到的唯一工作方式是將適配器重新分配到GridView
。
爲什麼沒有refreshDrawableState()
,invalidate()
,invalidateViews()
或notifyDataSetChanged
工作?他們爲什麼沒有視覺效果?
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridView letterGrid = (GridView) findViewById(R.id.letter_grid);
final LetterAdapter letterAdapter = new LetterAdapter(this);
letterGrid.setAdapter(letterAdapter);
Button shuffleButton = (Button) findViewById(R.id.shuffle_button);
shuffleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
letterAdapter.shuffle();
// --------------- RELEVANT PART
// letterGrid.refreshDrawableState();
// letterGrid.invalidate();
// letterGrid.invalidateViews();
letterGrid.setAdapter(letterAdapter);
// --------------- END
}
});
}
public class LetterAdapter extends BaseAdapter {
private Context mContext;
private BoggleBoard mBoggleBoard;
public LetterAdapter(Context context) {
mContext = context;
mBoggleBoard = new BoggleBoard();
}
public void shuffle() {
mBoggleBoard.shuffle();
notifyDataSetChanged();
}
@Override
public int getCount() {
return BoggleBoard.NUM_OF_CUBES;
}
@Override
public Object getItem(int position) {
return mBoggleBoard.getLetter(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Button letterButton;
final String curLetter = mBoggleBoard.getLetter(position);
if (convertView == null) {
letterButton = new Button(mContext);
letterButton.setText(curLetter);
} else {
letterButton = (Button) convertView;
}
return letterButton;
}
}
}
注:我已閱讀了大約一打相關的問題/答案,但找不到任何滿意的答案爲我的情況。
Ooops ..不應該錯過這個!謝謝! – kolistivra 2013-03-02 16:12:36