0

Concise: I am looking for a way to update a view in an activity from a fragment that the activity contains.

In detail: I have a fragment and an activity that contains the fragment. The activity has a navigation drawer and the navigation drawer contains a image view. What I am trying is to update the image view in the navigation drawer when a HTTP GET request returns a response from the fragment; the response contains a URL to where an image loader parses an image for the image view in the navigation drawer.

Given this, I am trying to get an instance of the view in the activity from the fragment, but I am not sure how to do so. Even, I am not sure if I am on the right direction...

I will greatly appreciate any input.

Regards,

makeasy
  • 907
  • 1
  • 6
  • 15
  • You can do this thing in your `FragmentDrawer` class. if you have. like one [HERE](http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/) – Devendra Singh Jan 26 '17 at 06:50

3 Answers3

8

Create Interface:

public interface mInterface{

  public void updateIMG(String url);

}

Implement this interface inside your activity and Override updateIMG() method.

Inside your fragment what ever you need to call updateIMG() just initiate interface and call a method.

mInterface listener =  (mInterface)getActivity();
listener.updateIMG(url);

Then you call this interface method it will run code inside overrided method inside activity.


In case you get Only the original thread that created a view hierarchy can touch its views., try.

Pablo
  • 1,953
  • 4
  • 28
  • 57
Vygintas B
  • 1,624
  • 13
  • 31
  • `mInterface listener = (mInterface)getActivity();` This line always gives me error `MainActivity cannot be cast to HomeFragment$OnMessageUpdateListener`. Please help. –  Dec 13 '21 at 10:57
0

Declare view as public which you want to update and then you can access that view from the fragment and can update from there

Rajesh Panchal
  • 1,140
  • 3
  • 20
  • 39
0

You can use a LocalBroadCast to send a broadcast from Fragment whenever needed and then receive the broadcast in Activity and do the changes.

You can also implement Activity, Fragment communication through an interface. Refer this link to implement the same.

arjun
  • 3,514
  • 4
  • 27
  • 48