AleCat83
AleCat83

Reputation: 1493

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

Upvotes: 3

Views: 3087

Answers (1)

Akshay Sharma
Akshay Sharma

Reputation: 418

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();

  ...
 }
}

Upvotes: 7

Related Questions