Question

I'm using a FragmentActivity with a FragmentStatePagerAdapter. In my fragments, I set click listeners on some views that respond by showing a Dialog. The Dialog layout is supplied via an XML layout resource, and some buttons in this layout use the onClick property to fire off a method in the FragmentActivity. And that works fine, the method gets called correctly when the buttons are clicked.

But I'd like to know how to get hold of a reference to the Dialog when the onClick method is called. All I have is the view (button) that was clicked, which is a child of the Dialog's layout. I actually just want to dismiss the dialog. And I'd really prefer not to have to make the Dialog some sort of global, static singleton or whatever, there must be a cleaner way. I'll try to illustrate it with some code:

public class MyFragment extends Fragment {
    ...
    ...
    @Override
    public View onCreateView(...) {
        ...
        dialogTrigger.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View src) {
                MyDialog dialog = new MyDialog(src.getContext());
                dialog.show();
            }
        });
    ...
}

public class MyActivity extends FragmentActivity {
    ...
    public void doIt(View src) {
        // dialog ref ???
    }
    ...
}

...and the Dialog layout XML:

<GridLayout ...>

    <Button
        ... 
        android:onClick="doIt" />
...
etc.
Was it helpful?

Solution

No, not the way you are doing it, because the dialog only exists once clicked. If however you move the declaration to a member variable, yes (as below)

 public class MyFragment extends Fragment {

    private MyDialog dialog;

    @Override
    public View onCreateView(...) {
        ...
        dialogTrigger.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View src) {
                dialog = new MyDialog(src.getContext());
                dialog.show();
           }
        });
        ...

       protected MyDialog getDialog() {
           return dialog.
       }
   }

   public class MyActivity extends FragmentActivity {

   public void doIt(View src) {
      //TODO: seems you want to do this too (?):  dialogTrigger.callOnClick();
      //EDIT: oops i missed the following the first time
      MyDialog dialog = ((MyFragment)getSupportFragmentManager().findFragmentById(R.id.my_fragment)).getDialog()
      ....
   }

There are better ways to handle such a situation though

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top