My question is if, while a Fragment is being visualized, is it still
Running the Activity in the background.
It does not really have an execution in the background since it does not call onPause () the Activity actually acts as a container that contains the Fragment
and you can even make transactions between Fragments
.
I know that when you press the onBackPressed () the Activity is called, but
I do not know if it's a special case or not.
It is not a special case, actually when you have implemented the onBackPressed()
method in the Activity
, when you execute this action it is actually called in Activity
.
@Override
public void onBackPressed()
{
// realiza acción en Activity
super.onBackPressed();
}
If you have a Fragment in an Activity and you want to emulate the same from the fragment it would have to be done by means of a interface :
This is a example :
// IMPLEMENTACION BASICA DE BACK EN FRAGMENT.
public abstract class BackHandledFragment extends Fragment {
protected BackHandlerInterface backHandlerInterface;
public abstract String getTagText();
public abstract boolean onBackPressed();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!(getActivity() instanceof BackHandlerInterface)) {
throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
} else {
backHandlerInterface = (BackHandlerInterface) getActivity();
}
}
@Override
public void onStart() {
super.onStart();
// Mark this fragment as the selected Fragment.
backHandlerInterface.setSelectedFragment(this);
}
public interface BackHandlerInterface {
public void setSelectedFragment(BackHandledFragment backHandledFragment);
}
}
Right now I have an Activity that sends data continuously, and
I'd like to run a Fragment while this happens.
You can easily make the transaction to add a Fragment:
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contenedor, OtroFragment.newInstance());
transaction.commit();
The Fragment for the visualization, and the Activity for the data Is
possible?
Actually a Fragment represents a behavior or a part of the user interface in an Activity. You can get the data at the beginning of Activity
and send them to instantiate the Fragment
, or even the same is important to mention that the Fragment
could perform both tasks.