Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call activity method from inner viewpager fragments

I'm working on an android app and I've got a viewPager with 4 fragments. In each fragment there are some input views.

Is it possible to declare a method in the activity that read each input view values, called on each input views status change?

Thank you

Alessandro

like image 269
AleCat83 Avatar asked Dec 04 '25 02:12

AleCat83


1 Answers

Yes, it is possible. Follow these steps.

  1. Make an interface and declare a method.
  2. Let the activity implement that interface
  3. Now override the method from interface and write the definition for the function.
  4. Make the object of the interface in the fragment.
  5. Using the object call that method whenever needed.

Example using code : -

Inteface Code :-

//use any name
public interface onInputChangeListener {

    /*To change something in activty*/
    public void changeSomething(//parameters that will hold the new information);


}

Activity Code:-

public class MyActivity extends AppCompatActivity implements onInputChangeListener {

    onCreate();

    @override
    public void changeSomething(/*Arguments with new information*/){

    //do whatever this function need to change in activity
    // i.e give your defination to the function
    }
}

Fragment Code:-

public class MyFragment extends Fragment {

    onInputChangeListener inputChangeCallback;

/*This method onAttach is optional*/
@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            inputChangeCallback = (onInputChangeListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement onFragmentChangeListener");
        }
    }


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

        View v = inflater.inflate(R.layout.fragment_my,container,false);
        inputChangeCallback.changeSomething(//pass the new information);
        return v;
    }

}

This would doo.. Cheers!

If you want a quick Fix :-

In your Fragment:-

public class MyFragment extends Fragment {

MyActivity myActivity;

 onCreateView(){
  ...

  myActivity = (MyActivity)getActivity;

  myActivity.callAnyFunctionYouWant();

  ...
 }
}
like image 83
Akshay Sharma Avatar answered Dec 06 '25 17:12

Akshay Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!