简体   繁体   中英

how to handle the fragment state when dialog dismissed

I have a ListView in a Dialog . When I select an item from the the list I dismiss the Dialog . Now the previous Fragment appears. I need to get the selected value from the 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();
    }
});

You need to add a listener to your Dialog . For example add something like this to you Dialog class:

private AddressListener addressListener;
public interface AddressListener {
    public void onSelected(Address address);
}

public AddressListener getAddressListener() {
    return addressListener;
}

public void setAddressListener(AddressListener addressListener) {
    this.addressListener = addressListener;
}

I recommend you also write a helper method to notify the listener:

protected void notifyAddressListener(Address address) {
    if(this.addressListener != null) {
        this.addressListener.onSelected(address);
    }
}

You then just have to call notifyAddressListener(...) in the OnItemClickListener to pass a value back to the listener:

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

In your Fragment or Activity or wherever you create and show the Dialog you have to set the AddressListener like this:

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

Of course you then have to implement the onSelected() method in your Fragment or Activity and as soon as the user picks an item in the Dialog onSelected() will be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM