the_prole
the_prole

Reputation: 8945

How to call a method two different classes have in common?

My question is a design question. I have two custom fragments CustomFrag1 and CustomFrag2. Both these fragments have a method swapCursor.

CustomFrag1:

public class CustomFrag1 extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        // .... code
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // .... code

        MyAdapter mAdapter = new MyAdapter(); 

        // .... code
    }

    public static void swapCursor(final Cursor cursor, Activity ctx){

        // .... code
    }

}

CustomFrag2:

public class CustomFrag1 extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        // .... code
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // .... code

        MyAdapter mAdapter = new MyAdapter(); 

        // .... code
    }

    public static void swapCursor(final Cursor cursor, Activity ctx){

        // .... code
    }

}

I don't want to make a seperate adapter class for each fragment. I do however, want to call swapCursor in the adapter class. If the adapter has been instantied from CustomeFrag1 I want swapCurosr to swap the cursor in CustomFrag1. If the adapter has been instantiated from CustomeFrag2 I want swapCurosr to swap the cursor in CustomFrag2.

Is it possible to pass in an instance of the Fragment...

MyAdapter mAdapter = new MyAdapter(this);

...and somehow represent that instance with a generic variable that has swapCursor defined as a method? If not, what strategy can I use? Interfaces? Generics? Something?

edit

I tried inheriting swapCursor but that would just swap out the cursor out on the parent and not the child.

Upvotes: 0

Views: 34

Answers (2)

Luca Nicoletti
Luca Nicoletti

Reputation: 2417

Use interfaces.

public interface SwapFrag { 
   public swapCursor(final Cursor cursor, Activity ctx);
}

your fragments need to implement SwapFrag:

public class CustomFrag1 extends Fragment implements SwapFrag

and also need to implements the swapCursor method.

@Override
public static void swapCursor(final Cursor cursor, Activity ctx) {
  ...
}

Upvotes: 0

pcjuzer
pcjuzer

Reputation: 2824

swapCursor shouldn't be static at the first place, because there's no inheritance for static methods.

You could create an interface (SwappableCursor as a name hint) which has a method swapCursor, then all of your fragments can implement this interface. So that you'll have to implement swapCursor.

In MyAdapter's constructor you can add a parameter which has the type of your interface (SwappableCursor). You'll be able to invoke swapCursor method.

Upvotes: 1

Related Questions