我试图在我的Android应用程序上从用户中选择项目到片段公式表,如下所示 谷歌文档 我试着在我的DialogFragment中实现这些方法和你的接口,并在我的fragment公式表中得到它,但是,当我点击打开Dialog Fragment所需的按钮时,错误被返回。
public class FiltroOpcao extends DialogFragment {
OnFiltroEscolhido listener;
private final String[] filtroAnuncio = getResources().getStringArray(R.array.filtro_array);
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
try {
listener = (OnFiltroEscolhido) getTargetFragment();
}catch(ClassCastException e){
throw new ClassCastException(context.toString()+"Deve ser implementado");
}
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Filtrar por:")
.setItems(R.array.filtro_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.pegarFiltro(filtroAnuncio[which]);
}
});
return builder.create();
}
public interface OnFiltroEscolhido{
void pegarFiltro (String escolha);
}
}
这是我的DialogFragment类: 我就是在这里调用DialogFragment的,而崩溃发生在我的VendaFragment片段类上。
public void onClick(View v) {
FiltroOpcao filtroOpcao = new FiltroOpcao();
filtroOpcao.setTargetFragment(VendaFragment.this, 1);
filtroOpcao.show(VendaFragment.this.getChildFragmentManager(), "FiltroOpcao");
}
private final String[] filtroAnuncio = getResources().getStringArray(R.array.filtro_array);
可能吧。getResources()
是问题所在,因为你是在片段被附加之前使用它。
尝试将 filtroAnuncio
到 onCreateDialog()
private String[] filtroAnuncio;
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
filtroAnuncio = getResources().getStringArray(R.array.filtro_array);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Filtrar por:")
.setItems(R.array.filtro_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.pegarFiltro(filtroAnuncio[which]);
}
});
return builder.create();
}