我有一段代码用于从GridD中选择一个AlertDialog中的数字:
public void iconSelect (View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
GridView gridview = new GridView(this);
List<Integer> mList = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
mList.add(i);
}
ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
gridview.setAdapter(adapter);
gridview.setNumColumns(3);
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Chosen: " + position, Toast.LENGTH_SHORT).show();
}
});
builder.setView(gridview);
builder.setTitle("Icon selector");
builder.show();
}
我的目标是当用户从gridview中选择一个数字时,对话框将关闭。现在,它允许用户点击gridview上的数字并按照用户的需要多次显示吐司,直到他按下后退按钮。
我该怎么办? 我正在寻找一个类似于builder.close()或builder.dismiss()的方法来在侦听器中执行。 (使构建器成为最终变量)
答案 0 :(得分:3)
您应该使用builder.show()
或builder.create()
来保存AlertDialog
的实例,以便在此之后将其解除
请尝试以下代码:
public void iconSelect (View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
GridView gridview = new GridView(this);
List<Integer> mList = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
mList.add(i);
}
ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
gridview.setAdapter(adapter);
gridview.setNumColumns(3);
builder.setView(gridview);
builder.setTitle("Icon selector");
final AlertDialog dialog = builder.show();
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Chosen: " + position, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}