[英]Getting null value in fragment spinner
我正在尝试在 Fragment 中使用过滤器并实现对话框片段。 这是我正在使用的课程
公共类 HomeFragment 扩展 Fragment 实现 FilterDialogFragment.FilterListener, PostAdapter2.OnPostSelectedListener{ 详细代码 }
这是用于微调器选择选项的基于对话框片段的类
公共类 FilterDialogFragment 扩展了 DialogFragment
单击过滤器按钮时会调用此方法,该按钮会弹出过滤器的微调选项对话框
已申报
private FilterDialogFragment mFilterDialog;
在 onCreateView
mFilterDialog = new FilterDialogFragment();
调用方法
public void onFilterClicked(){
mFilterDialog.show(getSupportFragmentManager(), FilterDialogFragment.TAG);
}
在此之后选择微调器选项并单击应用此方法被调用,其中mFilterListener为空,这不应该是这种情况
public interface FilterListener {
void onFilter(Filters filters);
}
FilterListener mFilterListener;
public void onSearchClicked() {
Log.d("Message", String.valueOf(mFilterListener));
if (mFilterListener != null) {
Log.d("Message", "New 55555");
mFilterListener.onFilter(getFilters());
}
dismiss();
}
请帮我解决这个问题。 如果需要更多详细信息,请告诉我
FilterDialogFragement 中的附加方法
public void onAttach(Context context) {
super.onAttach(context);
Log.d("Message", "New 6666666");
Log.d("Message", String.valueOf(mFilterListener));
if (context instanceof FilterListener) {
// Log.d("Message", String.valueOf(mFilterListener));
mFilterListener = (FilterListener) context;
}
}
我假设,你没有在mFilterDialog
设置监听mFilterDialog
,所以这就是为什么它为null
您正在尝试模仿这个库实现: Friendly Eats 。
但是,您不会批量复制它,主要是因为您选择使用implements FilterDialogFragment.FilterListener
HomeFragment
来启动FilterDialogFragment
,而不是库的MainActivity
。 这是您的空指针的原因。
这是由于getSupportFragmentManager()
工作方式。 如果你查看 Android 的文档,你会看到它说
返回 FragmentManager 以与与此活动关联的片段进行交互。 (我的粗体)
当你调用mFilterDialog.show(getSupportFragmentManager(), FilterDialogFragment.TAG);
在HomeFragment
,您实际上是在调用作为HomeFragment
父级的任何Activity
来启动新的FilterDialogFragment
。 您可以通过检查onAttach(Context context)
内的HomeFragment
onAttach(Context context)
context instanceof HomeFragment
来仔细检查这context instanceof HomeFragment
。 我不认为它会返回true
。
为了解决这个问题,并且不改变你对HomeFragment
的使用,你可以简单地传递一个HomeFragment
本身的实例,或者一个单独的FilterDialogFragment.FilterListener
实现(如果你不需要使用HomeFragment
任何东西而不是监听器,我更喜欢它) 在创建时或在您启动它之前添加到您的FilterDialogFragment
实例。
例如,您可以像这样创建一个公共 setter:
private FilterListener mFilterListener;
public void setFilterListener(FilterListener filterListener){
mFilterListener = filterListener;
}
然后在您的HomeFragment onCreateView()
,您执行以下操作:
mFilterDialog = new FilterDialogFragment();
//Or preferably, an anonymous/named implementing instance of the interface only.
mFilterDialog.setFilterListener(this);
这样做不会依赖 Android 框架来提供您的字段的初始化,并且不需要您更改您当前使用的Activity
或HomeFragment
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.