我正在为Android应用程序创建搜索页面。我想在某种模式中添加一些搜索过滤器,互联网上的建议说我应该使用带有片段的AlertDialog来显示我的自定义过滤器。我已设法在对话框中显示片段,但未调用与片段相关的代码(如onCreate)。当我直接在一个活动中使用片段时,会调用onCreate,但不会在AlertDialog加载它时调用它。有什么我做错了或者我应该采取另一种方式吗?
这是用于打开对话框的代码
SearchFilterDialogFragment dialog = new SearchFilterDialogFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
fragmentTransaction.remove(prev);
}
fragmentTransaction.addToBackStack(null);
dialog.show(fragmentTransaction,"dialog");
这是对话框配置的代码
public class SearchFilterDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.fragment_blank,null)).setTitle("Search Filters")
.setPositiveButton(R.string.filter_dialogue_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.filter_dialogue_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
这是最终会在其中包含实际过滤器的测试片段
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
答案 0 :(得分:1)
DialogFragment 片段。它管理Fragment生命周期。 BlankFragment中你想要的一切都应该在SearchFilterDialogFragment中。你不需要BlankFragment。
回答你的问题,为什么BlankFragment的代码没有被调用, 它是因为根本没有引用或实例化BlankFragment。 代码:
builder.setView(inflater.inflate(R.layout.fragment_blank,null))
将fragment_blank布局扩展到DialogFragment,但它不启动BlankFragment代码。
使用自定义setView正确使用DialogFragment :
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Set all the title, button etc. for the AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Search Filters");
//Get LayoutInflater
LayoutInflater inflater = getActivity().getLayoutInflater();
//Inflate the layout but ALSO store the returned view to allow us to call findViewById
View view = inflater.inflate(R.layout.fragment_blank,null);
//Do all the initial code regarding the view, as you would in onCreate normally
view.findViewById(R.id.some_view);
//Finally, give the custom view to the AlertDialog builder
builder.setView(view);
}