2013年9月10日 星期二

Use Bundle and static contructor wrapper to pass data

There's a way to define kinda a static custom constructor wrapper to pass in arguments to the real constructor :

public class HotkeyAppListDialog extends DialogFragment { 
    public static HotkeyAppListDialog newInstance(int position) {
        HotkeyAppListDialog frag = new HotkeyAppListDialog();
        Bundle args = new Bundle();
        args.putInt("position", position);
        frag.setArguments(args);
        return frag;
    }
   
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int position = getArguments().getInt("position");   
        ...
    }
}

public class HotkeySettings extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {                    
...
    }

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


沒有留言:

張貼留言