0

I am trying to put GPS coordinates on TextView of a Fragment from MainActivity but I can not figure out how to do this.

I have:

MainActivity.java
LocationFragment.java

I want to update an TextView in LocationFragment from MainActivity's onLocationChanged() method.

Is any chance to do this :

public void onLocationChanged(Location location) {

    lat = (double) (location.getLatitude());
    lng = (double) (location.getLongitude());

    fragment.updateText(lat +" "+lng);

}
imuraretu
  • 3
  • 4
  • You can pass the value from Activity to Fragment and display the same there. – Raghunandan Jun 20 '14 at 06:45
  • You can do what you are thinking of but of of course you need to save the current fragment visible in a variable or get the current one "on the fly" while you receive the new location. If you have multiple fragments, check the type of the fragment with "instanceOf" to be sure to run the method only for the correct fragment. – fasteque Jun 20 '14 at 06:54
  • It is a NavigationDrawer GUI and I have multiple fragments and i don't know how to select the right fragment and changing it's textView – imuraretu Jun 20 '14 at 07:10

2 Answers2

0

You can use Interface for it so main objective of Fragment re-usability is maintained. You can implement communication between Activity-Fragment OR Fragment-Fragment via using following :

enter image description here

Umang Kothari
  • 3,674
  • 27
  • 36
0

its very simple, just create one method in fragment like below,

public void SetTitle() {
        text_title.setText("hello fragment");
    }

now call that method from Activity, below code it for <= ANDROID API 11

HomeFragment fragment = (HomeFragment) getSupportFragmentManager()
                        .findFragmentByTag("HomeFragment");
                fragment.SetTitle();

for > 11 API just change getFragmentManager()

now you can do whatever you want.

Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177