我有一个OnClickListener打开一个带有listview的对话框和一个取消按钮,取消按钮自然地关闭对话框,但是我也想在点击listview上的一个项目并完成一些任务后关闭对话框,但是我无法弄清楚如何,这是我的代码:
View.OnClickListener clickListener = new View.OnClickListener()
{
TextView textView;
@Override
public void onClick(View view)
{
textView = (TextView) view;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AttendanceStatsActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.list_dialog, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Сурагчид");
alertDialog.setNegativeButton("Хаах", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.my_spinner_dropdown_item,
studentNames);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String fullName = studentNames.get(i);
textView.setText(fullName);
}
});
alertDialog.show();
}
};
我无法简单地调用dialog.dismiss(),因为它在onItemclick()中无法识别
答案 0 :(得分:1)
您需要将show
方法放在onItemClickListener
:
final AlertDialog dialog = alertDialog.show();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String fullName = studentNames.get(i);
textView.setText(fullName);
dialog.dismiss();
}
});
答案 1 :(得分:0)
您需要先声明dialog
变量。
//... above code
alertDialog.setTitle("Сурагчид");
// Get dialog here.
AlertDialog dialog = alertDialog.create();
// Now you can use
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
//Use it here. It is ok now
dialog.dismiss();
}
});
答案 2 :(得分:0)
试试这个:
如果您的任务已完成,请将alertDialog.dismiss()
放在lv.setOnItemClickListener中并删除dialog.dismiss();来自alertDialog.setNegativeButton
。