2013年9月11日 星期三

Refresh previous View from a Dialog

When returning from a Dialog, if want to refresh a previous View, say a list, the following code shows the way:

public class HotkeyAppListDialog extends DialogFragment {
    private AlertDialog mDialog;
    private static HotkeyListAdapter hotkey_list_adapter;

    public static HotkeyAppListDialog newInstance(int position, HotkeyListAdapter adapter) {
        HotkeyAppListDialog frag = new HotkeyAppListDialog();
        hotkey_list_adapter = adapter;
        return frag;
    }
   
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        HotkeyAppListAdapter adapter = new HotkeyAppListAdapter(getActivity(), R.layout.hotkey_app_list_row);
        ListView appList = new ListView(getActivity());  
        appList.setAdapter(adapter);
        appList.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        appList.setOnItemClickListener(new OnItemClickListener() {  
            public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
                Log.d("HotkeyAppListDialog", "position:"+position);
                hotkey_list_adapter.notifyDataSetChanged();
                mDialog.cancel();
            }
        });
        builder.setView(appList);
        builder.setTitle(R.string.hotkey_app_list_title);  
        mDialog = builder.create();
        return mDialog;
    }
}
 

public class HotkeySettings extends ListFragment {
    private HotkeyListAdapter hla;
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {                    
        View root = inflater.inflate(R.layout.hotkey_main, container, false);                    
        ListView list = (ListView) root.findViewById(android.R.id.list);
        hla = new HotkeyListAdapter(getActivity(), R.layout.hotkey_list_row);  
        hla.setNotifyOnChange(true);
        list.setAdapter(hla);
        return root;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        DialogFragment had = HotkeyAppListDialog.newInstance(position, hla);
        had.show(getActivity().getFragmentManager(), "hotkey app list");  
    }   
}


Reference links
http://stackoverflow.com/questions/15588538/android-listfragment-does-not-refresh

沒有留言:

張貼留言