当对话框被解除时如何处理片段状态

时间:2014-05-20 10:02:55

标签: android android-fragments android-dialogfragment

我在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();
    }
});

1 个答案:

答案 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();
    }
});

FragmentActivity或您创建的任何地方展示Dialog,您必须像这样设置AddressListener

ExampleDialog dialog = new ExampleDialog();
dialog.setAddressListener(this);
dialog.show();

当然,您必须在onSelected()Fragment中实施Activity方法,并且只要用户选择Dialog {{1}中的项目将被召唤。