pixel
pixel

Reputation: 10577

Activity Listener Implementation?

I am an Android/Java novice and I have a question based on following scenario:

  1. I have BaseActivity which is extended by number of other activities, say A1, A2, and A3
  2. Activities A1, and A2 may request user to enter some Part#s. Activity A3 doesn't have this functionality as it will never ask for a Part#.
  3. Part# is entered by user in a PartDialogFragment. Since user may be prompted for a Part# from A1 and A2 activities, I am thinking to put code that instantiates and shows my PartDialogFragment in BaseActivity so I don't have to duplicate same call in Activities A1 and A2.
  4. PartDialogFragment has interface that defines onPartEntered()

Question: Should I implement the interface from PartDialogFragment in BaseActivity or in activities A1 and A2?

Basically, I am thinking to do something like this:

class PartDialogFragment extends DialogFragment{
    private PartListener mPartListener;

    public interface PartNumberListener{
        void onPartEntered(String part#);
    }
    ...
    ...

  @Override
  public void onAttach(Activity activity){
    super.onAttach(activity);
    try{
      mPartListener = (PartListener) activity;
    } catch(ClassCastException e){
      throw new ClassCastException(activity.toString() + " must implement PartListener");
    }
  }
  ...
  ...
}

public abstract class BaseActivity 
  implements PartDialogFragment.PartNumberListener {  //**should I implement it here?**

    ...
    ...

    public void ShowPartNumberDialog(){
        //creates and shows PartDialogFragment defined above
    }
}

public class A1 extends Activity
  implements PartDialogFragment.PartNumberListener {  //**or in A1 and A2?**
    ...
    ...
    if (something){
        ShowPartNumberDialog();  //this is defined in BaseActivity
    }
}

public class A1 extends Activity
  implements PartDialogFragment.PartNumberListener {  //**or in A1 and A2?**
    ...
    ...
    if (something){
        ShowPartNumberDialog();  //this is defined in BaseActivity
    }
}

public class A3 extends Activity{
    ...
    ...
    //**this will never ask for Part#, so no need to implement PartDialogFragment.PartNumberListener here.**
}

Upvotes: 1

Views: 4120

Answers (2)

Vinicius DSL
Vinicius DSL

Reputation: 1869

A1 and A2 activities need to implement the interface, because if the base class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.

Upvotes: 1

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

You can have abstract PartActivity that will implement your onPartEntered logic. A1 and A2 will extend this PartActivity, A3 will extend BaseActivity directly, so it will not have this logic.

Upvotes: 1

Related Questions