Search code examples
androidandroid-fragmentsandroid-alertdialogandroid-dialogfragment

Clickable Hyperlinks in DialogFragment


This is my static inner class for creating an AlertDialog inside my MainActivity class:

public static class AboutDialogFragment extends DialogFragment {

    public static AboutDialogFragment newInstance() {
        AboutDialogFragment frag = new AboutDialogFragment();
        return frag;
    }  

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        return new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.ic_dialog_about)
                .setTitle(R.string.about)
                .setMessage(R.string.about_message)
                ..........
                .create();
    }
}

And I'm showing it when you press a menu item which is inside MainActivity:

case R.id.about:
        DialogFragment aboutFragment = AboutDialogFragment.newInstance();
        aboutFragment.show(getSupportFragmentManager(), "about_dialog");
        // Make links clickable
        ((TextView) aboutFragment.getDialog().findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
        return true;

I'm trying to make the links in the message text clickable using the commented line.

I found this method here and it has worked for me when using a regular Dialog (no fragments).
However, this is the first time I have tried using it on a DialogFragment and I always get a NullPointerException when trying to find the view.

I've also tried aboutFragment.getView().findViewById(android.R.id.message) but that returns null as well.

Maybe I am calling the code too early/in the wrong place?
Any ideas would be great!

EDIT: Just tried ((TextView) v.getRootView().findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); and ((TextView) v.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); in onCreateView() and also tried in onCreateDialog() without success.
Still getting null pointer exception...


Solution

  • Hopefully you've already figured this out but I just did this same thing and wanted to document it somewhere. Put this in your DialogFragment class:

    @Override
    public void onStart() {
        super.onStart();
        ((TextView) getDialog().findViewById(android.R.id.message))
                .setMovementMethod(LinkMovementMethod.getInstance());
    }