سؤال

I need to open a dialog from my custom component. To do this I need fragment manager, but I can't call getFragmentManager(): "The method getFragmentManager() is undefined for the type Context"

public class MyCustomButton extends Button {

    View.OnClickListener myOnlyhandler = new View.OnClickListener() {
        public void onClick(View v) {
            MyDialogFragment dialog = new MyDialogFragment();
            dialog.show(getFragmentManager(), "Tag");
        }
    };

}

Is there a better way to do this?

The buttons are placed in layout file:

<com.example.MyCustomButton android:id="@+id/myId1"/>
<com.example.MyCustomButton android:id="@+id/myId2"/>
<com.example.MyCustomButton android:id="@+id/myId3"/>

I need one listener for all of them.

هل كانت مفيدة؟

المحلول

It's better to create buttons programmatically and pass the context to the declared class like this. change your class to this:

public class MyCustomButton extends Button {
private Context context;
View.OnClickListener myOnlyhandler = new View.OnClickListener() {
    public void onClick(View v) {
        MyDialogFragment dialog = new MyDialogFragment();
        dialog.show(getFragmentManager(), "Tag");
    }
};
public void MyCustomButton(Context context){
   this.context=context;
   }
}

and then declare your button like this:

MyCustomButton button = new MyCustomButton(MainActivity.this);

then you have to add this view to main LinearLayout.

نصائح أخرى

You should pass a context into the constructor and then cast with an Activity or FragmentActivity to be able to get the FragmentManager or SupportFragmentManger:

public class MyCustomButton extends Button implements View.OnClickListener {

     private FragmentManager fragmentManager;

     public void MyCustomButton(Context context){
        fragmentManager = ((FragmentActivity) context).getFragmentManager();
        setOnClickListener(this);
     }

     @Override
     public void onClick(View v) {
        MyDialogFragment dialog = new MyDialogFragment();
        dialog.show(fragmentManager, "Tag");
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top