How to call an activity from a Dialogfragment in a

2019-09-21 05:09发布

问题:

I want to call an activity from Dialogfragment, I have attached the code and logcat below for your reference on what I have tried.Kindly provide me your knowledge on it. Thank you.

 Intent intent = new Intent(getActivity(), LinkActivity.class);
getActivity().startActivityForResult(intent, 0);

Logcat:

02-12 13:47:17.345: E/AndroidRuntime(670): FATAL EXCEPTION: main 02-12 13:47:17.345: E/AndroidRuntime(670): java.lang.NullPointerException 02-12 13:47:17.345: E/AndroidRuntime(670): at android.content.ComponentName.(ComponentName.java:75) 02-12 13:47:17.345: E/AndroidRuntime(670): at android.content.Intent.(Intent.java:3122) 02-12 13:47:17.345: E/AndroidRuntime(670): at com.firstadvantage.activities.LogDialog.LinkActivity(LogDialog.java:93) 02-12 13:47:17.345: E/AndroidRuntime(670): at com.firstadvantage.activities.LogDialog$3.onCommandFinished(LogDialog.java:75) 02-12 13:47:17.345: E/AndroidRuntime(670): at com.firstadvantage.buisnesslayer.commands.Command$3.run(Command.java:85) 02-12 13:47:17.345: E/AndroidRuntime(670): at android.os.Handler.handleCallback(Handler.java:605) 02-12 13:47:17.345: E/AndroidRuntime(670): at android.os.Handler.dispatchMessage(Handler.java:92) 02-12 13:47:17.345: E/AndroidRuntime(670): at android.os.Looper.loop(Looper.java:137) 02-12 13:47:17.345: E/AndroidRuntime(670): at android.app.ActivityThread.main(ActivityThread.java:4424) 02-12 13:47:17.345: E/AndroidRuntime(670): at java.lang.reflect.Method.invokeNative(Native Method) 02-12 13:47:17.345: E/AndroidRuntime(670): at java.lang.reflect.Method.invoke(Method.java:511) 02-12 13:47:17.345: E/AndroidRuntime(670): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 02-12 13:47:17.345: E/AndroidRuntime(670): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 02-12 13:47:17.345: E/AndroidRuntime(670): at dalvik.system.NativeStart.main(Native Method)

回答1:

There are two ways to call from Fragment to Activity that hosts the Fragment:

  1. Simply casting to HostActivity

    ((HostActivity) getActivity()).methodInActivity();
    
  2. Use interface in Fragment as listener, HostActivity implements the listener:

    private SuperListener hostActivity;
    
    //In Fragment, define interfce
    public interface SuperListener{
        //for example a confirm dialog
        void getDialogOk(View dialogView);
    }
    
    //in constructor, get listener instance from HostActivity
    public YourDialogFragment(SuperListener hostActivity)
    {
       this.hostActivity = hostActivity;
    }
    
    //when `Ok` clicked
    hostActivity.getDialogOk(dialogView);
    

Hope this is clear.