我的Android应用程序出现问题。这可能是一个简单的Java问题,但我不太清楚Java知道google的内容。下面是我所拥有的简化版本,说明了我的问题。我希望能够从对话框中访问gridview
。显然我在这里所做的不对。我尝试在onCreate方法之外移动声明,但随后我的应用程序在开始时崩溃(没有错误消息)。我也尝试将它作为参数添加到ShowDialog
,但我想因为我重写那个不起作用的函数。你可能会说,我不知道我在做什么。想法?
public class HelloGridView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
((ImageAdapter) gridview.getAdapter()).initializemThumbIds();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
showDialog(0);
}
});
}
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
gridview.setAdapter(new ImageAdapter(this)); // gridview cannot be resolved
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HelloGridView.this.finish();
}
});
AlertDialog diag = builder.create();
return diag;
}
}
答案 0 :(得分:1)
我认为你没有正确的范围,所以下面我将gridView作为成员变量。但我认为你真正想做的是让你的ImageAdapter成为一个成员变量,只在你的对话框中更新ImageAdapter&#34;是&#34;点击。
public class HelloGridView extends Activity {
private GridView gridview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
((ImageAdapter) gridview.getAdapter()).initializemThumbIds();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
showDialog(0);
}
});
}
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
gridview.setAdapter(new ImageAdapter(this)); // gridview cannot be resolved
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HelloGridView.this.finish();
}
});
AlertDialog diag = builder.create();
return diag;
}
}