Android Navigation Drawer unable to setText in a Fragment from MainActivity

a 夏天 提交于 2019-12-29 09:39:07

问题


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);

}

回答1:


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 :




回答2:


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.



来源:https://stackoverflow.com/questions/24321449/android-navigation-drawer-unable-to-settext-in-a-fragment-from-mainactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!