Reputation: 1493
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
Reputation: 418
Yes, it is possible. Follow these steps.
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