Reputation: 578
I have ViewPager with some Fragments, In one Fragment (in that ViewPager) I have a button, I want to update some information at Activity (which contains that ViewPager) by click the button. Anybody help me?
Upvotes: 1
Views: 69
Reputation: 2558
The best option is to use interface
Create the following Communicator.java
public interface Communicator {
public void respond(int i);
}
Implement this Communicator in your MainAcitvity
And create a instance
of this Communicator in your fragment like this
public class FirstFragment extends Fragment implements OnClickListener {
private Communicator com;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
com = (Communicator) getActivity();
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn:
com.respond(1);
break;
}
}
Whenever you click that button it sends the int to the method which is residing inside the MainActivity
which would look like following
public class MainActivity extends FragmentActivity implements Communicator{
@Override
public void respond(int i) {
int RECEIVED_VARIABLE = i;
}}
}
Here I'm receiving an int . You can use anything which you want
I hope this would help
Upvotes: 4