How do I call a child method from a parent class?

Let's say I have a ChildFragment class that inherits from ParentFragment. The goal is to have multiple Actions and Fragments with buttons, which are typically used with a single ParentFragment.

When the user clicks the refresh button, he calls the function refresh()

in ParentFragment

. However, the action of actually loading this file is handled by the ChildFragment because each fragment has different content. So I want this ParentFragment to call something on the child, whenever it is executed refresh()

.

How can i do this? Or, if there is a better way to do it, this will help too.

+3


source to share


4 answers


You need to override the method refresh

in child fragments.

public class PFragment extends Fragment{
  protected void refresh(){
    //Common stuff here
  }
}

      



In child class ovveride update method

public class CFragment extends PFragment{
 public void onClick(){
  super.refresh();
 }

@Override
protected void refresh(){
 //Custom stuff here
}

}

      

+5


source


class ParentFragment() {

    protected void refresh() {
        // general code when refresh every fragment
    }
}

class ChildFragment1 extend ParentFragment {
    @Override
    public void refresh() {
         super.refresh();
         // code for refresh child fragment1
    }
}

class ChildFragment2 extend ParentFragment {
    @Override
    public void refresh(); {
         super.refresh();
         // code for refresh child fragment2
    }
}

      



+1


source


If you don't want child classes to update and call super.refresh, define an abstract method in ParentFragment for the downloadFile method, and then implement it in the child (ren) classes:

class ParentFragment {
    public void refresh() {
        downloadFile();
    }

    protected abstract void downloadFile();
}

class ChildFragment extends ParentFragment {
    @Override
    protected void downloadFile() {
        // do the download here
    }
}

      

+1


source


EventBus ! - simplifies communication between components

+1


source







All Articles