In my app I got to a point where, in landscape mode, I need to attach two fragments. In order to do that, the second fragment needs to wait until the first fragment has been attached (added), before it's being added. The reason for it is that the first fragment needs to execute a function that the second fragment needs. I managed to do that via a thread, but in this case it only waits the amount of time indicated, before attaching the second fragment, and in case the first fragment isn't attached in the time given, the app will crush because the second fragment doesn't have the necessary data.
Any better practices (examples) then the code below (like waiting until the first fragment is attached, and no on a certain time interval) ? :
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.mainContent, fragment).commit();
Thread thread = new Thread() {
@Override
public void run() {
try {
synchronized (this) {
wait(1000);
}
} catch (InterruptedException e) {
}
if (isLandscape) {
openSecondFragment(mIndex, R.id.rightConent);
}
}
};
thread.start();
Much appreciated.
The handler i need to be executed in the first fragment:
@SuppressLint("HandlerLeak")
protected void loadAccountList() {
LoadAccountList loadAccountListThread = new LoadAccountList(new Handler() {
@SuppressWarnings("unchecked")
public void handleMessage(Message msg) {
switch (msg.what) {
case LOAD_SUCCESSFUL_CODE:
items = (ArrayList<Account>) msg.obj;
break;
case LOAD_FAILED_IOEXCEPTION_CODE:
getActivity().showDialog(ERROR_DIALOG);
break;
default:
break;
}
}
});
loadAccountListThread.start();
Fragments lifecycle works in your favor here. According to the documentation the method onStart() is "Called when the Fragment is visible to the user", so I suggest you do something like this in your first fragment class:
public void onStart() {
super.onStart();
((MainActivity)getActivity()).loadSecondFragment();
}
And in your Activity:
public void loadSecondFragment() {
if (isLandscape) {
openSecondFragment(mIndex, R.id.rightConent);
}
}
And voilá! Try any of the lifecycle methods and see which one works best for your purpose.
You can observe Fragments creation by registering FragmentLifecycleCallbacks in FragmentManager.
Implement callbacks of Your interest such as onFragmentAttached, onFragmentResumed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With