我正在尝试通过扩展 ListFragment 的 Fragment 的 onActivityCreated 方法设置 DialogFragment 的标题。
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
ListView lv = this.getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
android.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
RatingDialogFragment newFragment = new RatingDialogFragment();
newFragment.getDialog().setTitle("String");
fragmentTransaction.add(newFragment, "dialog");
newFragment.show(fragmentTransaction, "dialog");
return true;
}
});
}
这会产生一个空指针异常,因为 DialogFragment 的 mDialog 仍然是空的。
参见:DialogFragment.getDialog returns null
关于如何解决这个问题有什么想法吗?
最佳答案
解决此问题的一种可能方法是让正在创建的 Fragment
决定何时可以安全地设置其标题。
例如,您可以在构造函数中传递标题并将其保存在成员变量中。
RatingDialogFragment newFragment = new RatingDialogFragment("String");
然后在您的 RatingDialogFragment 中:
...
public RatingDialogFragment(String title) {
mTitle = title;
}
...
在您的 RatingDialogFragment 生命周期的某个地方,当这样做是安全的时候,实际设置标题。
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Set title for this dialog
getDialog().setTitle(mTitle);
}
编辑:值得注意的是,虽然这在这种特殊情况下有效,但更好的通用方法是使用 Fragment
通过 setArguments()
和getArguments()
方法。这允许您保留默认的空构造函数,以便框架可以正确实例化您的 fragment (例如,如果您通过 XML 引入 fragment )。一个例子可以是 found here。
从 documentation 开始:
Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().
关于android - 从 ListFragment 调用 DialogFragment 上的 setTitle(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428032/