我在ListView
中有一个Dialog
。当我从列表中选择一个项目时,我会忽略Dialog
。现在出现了之前的Fragment
。我需要从Dialog
获取所选值。
addressListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
addr = (Address) addressListView.getItemAtPosition(position);
AppUtils.printLog("selected",addr.getLatitude()+","+addr.getLongitude());
dismiss();
}
});
答案 0 :(得分:2)
您需要为Dialog
添加一个监听器。例如,向Dialog
类添加类似这样的内容:
private AddressListener addressListener;
public interface AddressListener {
public void onSelected(Address address);
}
public AddressListener getAddressListener() {
return addressListener;
}
public void setAddressListener(AddressListener addressListener) {
this.addressListener = addressListener;
}
我建议您也编写一个帮助方法来通知监听器:
protected void notifyAddressListener(Address address) {
if(this.addressListener != null) {
this.addressListener.onSelected(address);
}
}
然后,您只需在notifyAddressListener(...)
中调用OnItemClickListener
即可将值传回给侦听器:
addressListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
addr = (Address) addressListView.getItemAtPosition(position);
AppUtils.printLog("selected",addr.getLatitude()+","+addr.getLongitude());
// Notify listener
notifyAddressListener(addr);
dismiss();
}
});
在Fragment
或Activity
或您创建的任何地方展示Dialog
,您必须像这样设置AddressListener
:
ExampleDialog dialog = new ExampleDialog();
dialog.setAddressListener(this);
dialog.show();
当然,您必须在onSelected()
或Fragment
中实施Activity
方法,并且只要用户选择Dialog
{{1}中的项目将被召唤。