I am trying to build an app with one MainActivity and multiple fragments.
In my MainActivity, I get the data and store it in the Data Model. For example, getting sunrise time, then display it in Fragment B. How can I detect the sunrise value changes and update the TextView in Fragment without restarting the app? Is there way can listen to value changed and update the textView?
here are my codes and fragment B layout.
JAVA data model CLASS
public class SunriseTimeClass {
private static final SunriseTimeClass INSTANCE = new SunriseTimeClass();
public String sunrise = "";
private SunriseTimeClass(){ }
public static SunriseTimeClass getInstance(){
return INSTANCE;
}
}
MAINACTIVITY
override fun onCreate(savedInstanceState: Bundle?) {
//this will clear the back stack and displays no animation on the screen
var sunRise = SunriseTimeClass.getInstance()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayShowHomeEnabled(true)
getSunriseSunset()
}
fun getSunriseSunset(){
val location = com.luckycatlabs.sunrisesunset.dto.Location("40.9167654", "-74.171811")
val calculator = SunriseSunsetCalculator(location, "America/New_York")
sunRise.sunrise = calculator.getOfficialSunriseForDate(Calendar.getInstance())
}
FRAGMENT B layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:gravity="center"
android:id="@+id/DisplaySunrise"/>
</FrameLayout>
There are two possible ways to approach this.
FragmentB gets the sunRise data and updates its own TextView
Have
FragmentB
retrieve the sunRise values directly and update itsTextView
, rather than performing the retrieval inMainActivity
.OR
Communicate between Activity and Fragment via an interface
This answer is similar to another one in this thread, but is more explicit on how you would set the fragment's
TextView
. This solution makes several assumptions and may be an oversimplification due to the limited information in your question:Assumption 1: This solution assumes that the
getSunriseSunset
method is synchronous, i.e. not dependent on any service or network call. If it is asynchronous, you would need a separate callback in yourMainActivity
(e.g.onSunriseRetrieved
) to listen for when your data is returned, prior to updating your fragment.Assumption 2: This solution also assumes that you want access to the fragment's views immediately after it has been added (hence, the
executePendingTransactions
call). That said, if you have FragmentB perform its own retrieval of the sunRise, then this assumption wouldn't be needed.Define an interface in the Activity and :
Have FragmentB implement the interface: