我在让 GridView 在滚动时保持其数据一致时遇到问题。基本上,我正在开发一个简单的宾果游戏应用程序,我希望能够在屏幕上滚动,以便用户可以看到完整的 5x5 网格。我一直在使用这个问题来试图弄清楚发生了什么(Android:在 OnItemClick 之后替换 GridView 数组中的图像)如果我理解正确,我需要修改 getView() 以不为每个单元格使用回收视图。这是我到目前为止所拥有的:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView gridview = (GridView) findViewById(R.id.gridview);
final Bingo bingo = new Bingo();
final String[] stuff = new String[25];
for (int i=0;i<25;i++){
stuff[i]=bingo.getValue(i);
}
stuff[12]="Free Space";
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stuff);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
bingo.open(position);
if (bingo.isOpen(position))
v.setBackgroundColor(Color.rgb(12, 15, 204));
else
v.setBackgroundColor(Color.rgb(128, 128, 128));
if (bingo.bingo()==true){
Toast.makeText(getApplicationContext(),
//((TextView) v).getText(),
"BINGO",Toast.LENGTH_SHORT).show();
}
}
});
}
这种代码有点工作。背景发生了变化,它与我的宾果游戏类界面很好,但是当滚动时,随机单元格会改变颜色,有时单元格值会消失,留下空白。我在适配器声明之后尝试了以下代码,但它在设备上加载后立即崩溃。
{
public View getView(int position, View convertView, ViewGroup parent){
Context mContext = null;
TextView textView= new TextView(mContext);
if (convertView == null) {
textView.setText(stuff[12]);
} else {
textView = (TextView) convertView;
}
if (bingo.isOpen(position))
textView.setBackgroundColor(Color.rgb(12, 15, 204));
else
textView.setBackgroundColor(Color.rgb(128, 128, 128));
return textView;
}
};
我只是在理解如何使它适用于文本视图时遇到问题。对此的任何帮助将不胜感激。