我正在尝试创建一个DialogFragment,它显示一个带有自定义ListView的对话框.
@H_404_11@解决方法
public class MultiSelectDialogCustom extends DialogFragment { ListView mLocationList; private ArrayList<String> mOfficeListItems = new ArrayList<String>(); public static MultiSelectDialogCustom newInstance(int title) { MultiSelectDialogCustom dialog = new MultiSelectDialogCustom(); Bundle args = new Bundle(); args.putInt("title",title); dialog.setArguments(args); return dialog; } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { Collections.addAll(mOfficeListItems,getResources().getStringArray(R.array.offices)); View v = inflater.inflate(R.layout.fragment_choice_list,container,true); mLocationList = (ListView)v.findViewById(R.id.location_criteria_list); final FunctionListArrayAdapter adapter = new FunctionListArrayAdapter( this,android.R.layout.simple_list_item_1,mOfficeListItems); mLocationList.setAdapter(adapter); getDialog().setTitle(getArguments().getInt("title")); return v; } }
从片段中调用时:
MultiSelectDialogCustom dialogFrag = MultiSelectDialogCustom_.newInstance(R.string.dialog_title); dialogFrag.show(getActivity().getSupportFragmentManager(),null);
你应该重写onCreateDialog而不是使用onCreateView,它应该看起来像:
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { Collections.addAll(mOfficeListItems,getResources().getStringArray(R.array.offices)); View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_choice_list,null); mLocationList = (ListView)v.findViewById(R.id.location_criteria_list); final FunctionListArrayAdapter adapter = new FunctionListArrayAdapter( this,mOfficeListItems); mLocationList.setAdapter(adapter); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getArguments().getInt("title")).setView(v); return builder.create(); }
DialogFragment documentation page的引用描述了您要做的事情:
Implementations should override this class and implement
onCreateView(LayoutInflater,ViewGroup,Bundle)
to supply the content of the dialog. Alternatively,they can overrideonCreateDialog(Bundle)
to create an entirely custom dialog,such as anAlertDialog
,with its own content.