ZenBalance
ZenBalance

Reputation: 10307

Dynamically change ViewpagerIndicator Fragment Content Android

I am working on an application using viewpagerindicator.

In my main activity that has the viewpagerindicator, I spin off a thread that does some computation and updates a an instance variable mString of the activity. I want to update a fragment in the viewpagerindicator with the mString. However, I can't seem to figure out the best way to reach the fragment.

Does anyone know of any good samples that do something similar to this?

Upvotes: 1

Views: 1307

Answers (2)

faylon
faylon

Reputation: 7440

You want to update the UI of a Fragment in ViewPager after it is started, do i make it clear?

Ok, in this situation

  1. You should add a public method in your custom Fragment.
  2. Find the Fragment in your Activity.
  3. Invoke the method after your calculation is done.

The question is same with this one.

Upvotes: 1

straya
straya

Reputation: 5059

Create a callback object in your Fragment, register it with your FragmentActivity. If mString is already set in FragmentActivity then you can return it immediately via the callback, otherwise, when the computation thread finishes, it can return the string via the callback. The callback method should do whatever the Fragment needs to do with the string, e.g. set the text of a TextView.

E.g. create an interface called DynamicDataResponseHandler as follows:

public interface DynamicDataResponseHandler {
   public void onUpdate(Object data);
}

Then in your Fragment, implement that interface as follows:

private class MyStringDataResponseHandler implements DynamicDataResponseHandler {
   @Override
   public void onUpdate(Object object) {
      mYourTextView.setText((String)object);
   }
}

Your Fragment can then instantiate a MyStringDataResponseHandler object in its onCreate, pass that to the FragmentActivity via a method in the FragmentActivity like:

private MyStringDataResponseHandler mMyStringDataResponseHandler;

public void registerMyStringDataResponseHandler (DynamicDataResponseHandler callback) {
   mMyStringDataResponseHandler = callback;
   if(mString != null) {
      mMyStringDataResponseHandler.onUpdate(mString);
   }
}

And wherever in your Handler you obtain the value for mString, do something like this:

if(mMyStringDataResponseHandler != null) {
   mMyStringDataResponseHandler.onUpdate(mString);
}

Do some reading on the concept of Callbacks to get a better understanding of what I'm doing above and other ways you can use them.

Upvotes: 1

Related Questions