简体   繁体   English

Android 侦听器始终为 null 附加在 DialogFragment 中时

[英]Android listener always null when attach in a DialogFragment

high school teachers here trying to teach how to implement a DialogFragment with listener attach with an interface to the fragment that show it.这里的高中老师试图教授如何实现带有监听器的 DialogFragment 以及显示它的片段的接口。 for some reason the listener is always null and while the dialog show, when I press the ok or Cancel button of the Dialog, the transfert to the implement method dont work, it stop a the line where I call the listener class (always null) in the alertDialog.Builder Here my code, thank出于某种原因,侦听器始终为 null,而对话框显示时,当我按下对话框的确定或取消按钮时,转移到实现方法不起作用,它停止了我调用侦听器 class(始终为空)的行在 alertDialog.Builder 这是我的代码,谢谢

here my Fragment that call the dialogfragment这里是我的调用 dialogfragment 的片段

    package net.ccl.monapp.ui;

import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.ccl.monapp.R;


public class AnimationFragment extends Fragment implements MonDialogFragment.MonDialogListener {


    public AnimationFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_animation,container,false);
        Button myButton = root.findViewById(R.id.bt_dialog);
        final TextView tvTitre = root.findViewById(R.id.tv_titre);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DialogFragment myDialog = new MonDialogFragment();

                // Show Alert DialogFragment
                myDialog.show(getFragmentManager(), "Dialog");
            }
        });

        return root;
    }





    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        TextView myTitre = getView().findViewById(R.id.tv_titre);
        myTitre.setText("Mon nouveau titre");
        dialog.dismiss();
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        Toast.makeText(getActivity(),"Vous avez canceler l'action du dialog",Toast.LENGTH_SHORT);
    }
}

here my DialogFragment这是我的 DialogFragment

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;




public class MonDialogFragment extends DialogFragment {
    public MonDialogFragment() {

    }

    public interface MonDialogListener {
        void onDialogPositiveClick(DialogFragment dialog);
        void onDialogNegativeClick(DialogFragment dialog);
    }

    // Use this instance of the interface to deliver action events
    public MonDialogListener listener;



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            listener = (MonDialogListener) context;
        } catch (ClassCastException e) {

        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {


        AlertDialog.Builder builder =  new AlertDialog.Builder(getActivity());

        builder.setTitle("Mon interface dialog");

        builder.setMessage("Ceci est un message qui explique que tu peux changer le titre du fragment animation en cliquant sur ok");

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        listener.onDialogPositiveClick(MonDialogFragment.this);

                    }
                });

        builder .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        listener.onDialogNegativeClick(MonDialogFragment.this);
                    }
                });

        return builder.create();
    }


}

and here my logcat这是我的 logcat

 Process: net.ccl.monapp, PID: 13691
java.lang.NullPointerException: Attempt to invoke interface method 'void net.ccl.monapp.ui.MonDialogFragment$MonDialogListener.onDialogPositiveClick(androidx.fragment.app.DialogFragment)' on a null object reference
    at net.ccl.monapp.ui.MonDialogFragment$1.onClick(MonDialogFragment.java:56)
    at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Your onAttach() isn't actually doing anything since the Context you're attempting to cast is your Activity , not your AnimationFragment .你的onAttach()实际上并没有做任何事情,因为你试图投射的Context是你的Activity ,而不是你的AnimationFragment

Instead of reaching up to get your listener, your AnimationFragment should set the listener on the Dialog by overriding onAttachFragment() .您的AnimationFragment应该通过重写onAttachFragment()在 Dialog 上设置侦听器,而不是伸手去获取您的侦听器。

First, you need to make sure that your MonDialogFragment is a child fragment of your AnimationFragment by changing your show() to use getChildFragmentManager() :首先,您需要通过将show()更改为使用getChildFragmentManager()来确保您的MonDialogFragmentAnimationFragment的子片段:

myDialog.show(getChildFragmentManager(), "Dialog");

Then, override onAttachFragment() in your AnimationFragment :然后,在您的AnimationFragment中覆盖onAttachFragment()

@Override
public void onAttachFragment(Fragment fragment) {
    super.onAttachFragment(fragment);

    if (fragment instanceof MonDialogFragment) {
        ((MonDialogFragment) fragment).listener = this;
    }
}

You can then remove onAttach() from MonDialogFragment entirely.然后,您可以从MonDialogFragment完全删除onAttach()

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

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