繁体   English   中英

IllegalStateException:Fragment FiltroOpcao 未附加到上下文。- Android 错误

[英]IllegalStateException: Fragment FiltroOpcao not attached to a context.- Android Error

我正在尝试在我的 Android 应用程序上从用户中选择项目到片段公式,按照谷歌文档,这可以使用库中的这个方法,我尝试在我的 DialogFragment 中实现这个方法和你的接口,并在我的片段公式中获取它,但是,当我单击打开对话框片段所需的按钮时,会返回错误。 这是我的对话片段 class:

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 的地方,崩溃发生在我的 VendaFragment 片段 class

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();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM