Similar onBackPressed() for Fragments? - android

Hello my Android application is using fragments. I am wondering if there is a way I can use the idea of the onBackPressed() method in my app with fragments. I have previous and next buttons, but as of now I am just creating new fragments and replacing, and none of the data gets saved. Is there a way to save my data/go back once I have gone forward?

The concept of Fragment is different of Activity.
One Activity could have a many Fragments, read that:
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities. You
can think of a fragment as a modular section of an activity, which has
its own lifecycle, receives its own input events, and which you can
add or remove while the activity is running (sort of like a "sub
activity" that you can reuse in different activities).
See more here: http://developer.android.com/guide/components/fragments.html
SOLUCTION
So if you wanna handle the onBackPressed behavior in you Fragment you could do that:
package com.example.stackoverflowsandbox;
import android.app.Activity;
import android.app.Fragment;
public class MainActivity extends Activity {
public class MyFragment extends Fragment {
public void onBackPressed() {
// your code here...
}
}
private MyFragment myFragment;
#Override
public void onBackPressed() {
// super.onBackPressed(); // comment to not back
this.myFragment.onBackPressed(); // the onBackPressed method of Fragment is a custom method
}
}

Sorry, do not know if I understand your question, but if the idea and have control of direct backbutton in its fragment, and from it to perform some task of data persistence, you can add your fragment to control stack FragmentManager, the as follows.
FragmentManager fm = getSupportFragmentManager();
MyFragment mMyFragment = new MyFragment();
fm.beginTransaction()
.add(mMyFragment, "mMyFragment")
.addToBackStack( null )
.commit();
In the fragment you need to implement the interface OnBackStackChangedListener
In Fragment:
public class MyFragment extends Fragment implements OnBackStackChangedListener {
#Override
public void onBackStackChanged() {
//your code here
}
}
If you just keep the values
public class MyFragment extends Fragment {
String valeu;
#Override
public void onCreate( final Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
if ( savedInstanceState != null ) {
this.valeu = savedInstanceState.getString( "key" );
}
}
#Override
public void onSaveInstanceState( final Bundle outState ) {
super.onSaveInstanceState( outState );
outState.putString( "key", "Your content" );
}
}

while moving to front fragment, save the state of previous fragment using onSaveInstanceState()
while moving back restore the state in onCreate() or onCreateView() in the previous fragment

Related

Fragment communication: which is the better approach?

I was working on communication between multiple fragments in a activity stack.
I have figured out 2 ways to do this.
Through interfaces
Through Bundle setarguments
Bundle bundle = new Bundle();
bundle.putBoolean("Status",trur);
Fragment fragment = getFragmentManager().findFragmentByTag(bottomfragment.class.getName());
if(fragment!=null) {
fragment.setArguments(bundle);
}
I felt the 2nd approach easy.Since Google recommends 1 st approach
Can anyone help me with the problems I may face by following 2nd approach.
You are mixing the both the ways.
1. through interfaces is if you want to communicate from fragment to activity or fragment to fragment(via activity)
2. set argument is if you want to pass arguments while starting the fragment. you can call methods of fragment using the instance you get from fragment id/tag
Please referfragment communication
Try to communication between two fragments like this:
1) Create Interface like this:
public interface FragmentChangeListener {
void changeFragment(Fragment fragment);
}
2) Update MainActivity like this:
public class MainActivity extends AppCompatActivity implements FragmentChangeListener
{
//Activity code
------
#Override
public void changeFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction tr = fm.beginTransaction();
tr.replace(R.id.frame_container, fragment);
tr.commitAllowingStateLoss();
}
}
3) Create First Fragment:
public class FirstFragment extends Fragment
{
// call another freagment like this
//in your oncreateview method:
SecondFragment
Bundle b = new Bundle();
b.putSerializable(SELECTED_ITEM, true);
SecondFragment second = SecondFragment.newInstance(b);
FragmentChangeListener fc = (FragmentChangeListener) getActivity();
fc.changeFragment(second);
}
4) Second Fragment:
public class SecondFragment extends Fragment
{
public static SecondFragment newInstance(Bundle bundle) {
SecondFragment fragment = new SecondFragment();
if (bundle != null)
fragment.setArguments(bundle);
return fragment;
}
//another fragment related code
//In your OncreateView like this:
if (getArguments() != null)
boolean temp = getArguments().getBoolean(IntentParameter.SELECTED_ITEM);
}
Hope this explanation help you :)
Argument (Bundle) should be passed to Fragment only initially (when Fragment's object is created by default constructor). Calling setArguments method on already added Fragment will cause IllegalStateException. See body of setArguments method:
public void setArguments(Bundle args) {
if (mIndex >= 0 && isStateSaved()) {
throw new IllegalStateException("Fragment already active and state has been saved");
}
mArguments = args;
}
If you want to change something in Fragment A from Fragment B :
a) Get an object of A inside B using
getFragmentManager().findFragmentByTag("FRAGMENT_A_TAG");
Or
getFragmentManager().findFragmentById(FRAGMENT_A_CONTAINER_ID);
Cast returned object to A and call proper method on it. (It's the simplest way, but after it, A and B become highly coupled);
b) Alternatively, you can write mentioned logic inside method of Activity, which contains these 2 Fragments, get reference of this Activity inside B using getContext() casted to container Activity and call mentioned method on it (It kills reusability, because if you want to have A and B on other Activity, casting getContext() will cause ClassCastException);
c) The best way, to communicate between Fragments is to create interface, implement container Activity by this interface, get reference of this interface inside B and call proper method on it. (You can implement as many activities as you want by this interface, so it's reusable approach and A and B are loosely coupled).

transfer data from fragment A -> fragment B - > fragment C. When user click Back button, I want to return to fragment A and data

I'm a newbie in android developer. I have a question about transfer with 3 fragments.
I have 3 fragments (A - B - C). I want o transfer data from A -> B -> C.
In each the fragment, data was been changed.
When user click BACK BUTTON, user want to return A with the updated data.
How to return fragment A with the update data?
Thanks.
Here is a sample idea how to achieve communication.
// activity classs
public class SampleActivity extends Activity implements OnFragmentChangeListener {
OnBackPressListener dataFragment;
public void onCreate(bundle){
android.app.FragmentManager fragmentManager=getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
dataFragment = new DataFragment();
fragmentTransaction.add(R.id.audio_permission_button,dataFragment);
fragmentTransaction.commit()
}
#override
public void OnFragmentChange(Bundle bundle){
//here you go.
// write code to load new fragment with same idea. now you have bundle do what you want.
}
#Override
public void onBackPressed() {
// you can call this method from any click event, This just an sample idea.
dataFragment.OnActivityBackPress();
}
}
// interface to communicate with fragment
public interface OnFragmentChangeListener {
public void OnFragmentChange()
}
// fragment class
public class DataFragment extends Fragment implements OnBackPressListener {
OnFragmentChangeListener onFragmentChangeListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onFragmentChangeListener=(OnFragmentChangeListener) getActivity();
}
#Override
public void OnActivityBackPress() {
// pass you data to activity for loading new fragment or to refresh data.
Bundle bundle= new Bundle();
onFragmentChangeListener.OnFragmentChange(bundle);
}
}
// interface behave like mediator
public interface OnBackPressListener {
public void OnActivtiyBackPress();
}
Use interface to achieve this. Implements interface in fragment and activity, as it's a good way to communicate between fragment through activity. Then send the data through interface and extract the data from it.
You can use Interface class to communicate between fragment but it must make sure all the fragment is alive.
You can use SharedPreferences where you can save the data and retrieve it anywhere you like

Call a function of Activity from a fragment

I want to call the function Ask() of MainActivity from fragment2.
How can I call a function of MainActivity from fragment2?
I want to import results into a page called from fragment2.
Edit:
I already see that discussion, but don't have the solution of my problem.
Make that function static, after that you can access that function in Fragment e.g. MainActivity.Ask();
From fragment to activty:
((YourActivityClassName)getActivity()).yourPublicMethod();
From activity to fragment:
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
Cheers!
I would recommend you read this documentation.
call to function Ask() of MainActivity from fragment2.
For this you need a create a interface in your fragment2. The below code is an example from the document. You shouldn't ignore the onAttach method in your fragment as well.
public class Fragment2 extends ListFragment {
OnCallActivityListener mCallback;
// Container Activity must implement this interface
public interface OnCallActivityListener {
public void callAskMethod();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnCallActivityListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
Now the fragment can deliver messages to the activity by calling the callAskMethod() method (or other methods in the interface) using the mCallback instance of the OnCallActivityListener interface.
For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.callAskMethod();
}
After that you should implement the interface in your host activity.
public static class MainActivity extends Activity
implements Fragment2.OnCallActivityListener{
...
public void callAskMethod() {
// Do something here
ask();
}
}
So that is it. You have called ask() method from fragment2 fragment.
I want to import results into a page called from fragment2.
The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.
In your `MainActivity you can call send the result to the fragment.
Fragment2 fragment2 = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.article_fragment);
So you have a instance value of the Fragment2 in MainActivity. So you can any public method of the fragment2 from there.
for example
fragment2.doSomething();
That's it.

Android Fragments - Should we really save state?

I have implemented a simple activity with this code:
public class MainActivity extends AppCompatActivity implements Fragment_1.Operations{
Fragment_1 fragment_1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentactivity);
fragment_1=(Fragment_1)getSupportFragmentManager().findFragmentByTag("fragment_1");
}
//called on buttonclick, fired from a button existing in R.layout.fragmentactivity
public void createFragment(View view){
if (getSupportFragmentManager().findFragmentByTag("fragment_1")==null){
fragment_1=new Fragment_1();
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentactt,fragment_1,"fragment_1");
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
else{
fragment_1=(Fragment_1)getSupportFragmentManager().findFragmentByTag("fragment_1");
}
//Simply adding item to the listview contained in fragment_1.
fragment_1.add("Project #1");
fragment_1.add("Project #2");
fragment_1.add("Project #3");
}
//callback of interface "Operations"
#Override
public void buttonClicked() {
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
if (fragment_1.isAdded()){
transaction.remove(fragment_1);
//transaction.addToBackStack(null);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
}
}
Well, the doubt came from the fact that no "onSaveInstanceState" needed to be implemented, everything got "saved" without any problems.
So, why should i use putfragment and getFragment? Do these methods need to be called in order to avoid that, when OS kills app process, they would be lost? This is the only reason i can imagine to force onSaveInstanceState and onRestoreInstanceState methods.
Any help is appreciated.
Activity and fragment lifecycles are linked so when any callback method such as onResume is called for the activity, it is called for the fragment too.
putFragment and getFragment help the activity to manage its fragment child's lifecycle. The activity also has to save instance state.
In order to be activity independant, a fragment can manage his own instance state.

Fragment: which callback invoked when press back button & customize it

I have a fragment:
public class MyFragment extends Fragment{
...
#Override
public View onCreateView(...){...}
...
}
I instantiate it:
MyFragment myFragment = new MyFragment();
I use the above fragment to replace the current fragment:
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// replace fragment
fragmentTransaction.replace(R.id.fragment_placeholder, myFragment, "myTag");
// NOTE: I did not add to back stack
Now, myFragment is showing on the screen. NOTE: I did not add myFragment to back stack.
My two questions:
1. If now, I press mobile phone back button, which fragment's life cycle callback will be invoked??
2. How can I customize the back button click listener in MyFragment class? (please do not suggest me to do myFragment.getView().setOnclickListener, but do it in MyFragment class)
Question 1: See http://developer.android.com/reference/android/app/Fragment.html#Lifecycle:
"As a fragment is no longer being used, it goes through a reverse series of callbacks:
onPause() - fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is
modifying it in the activity.
onStop() - fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it
in the activity.
onDestroyView() - allows the fragment to clean up resources associated with its View.
onDestroy() - called to do final cleanup of the fragment's state.
onDetach() - called immediately prior to the fragment no longer being associated with its activity."
Question 2: If you must know that it was the back button specifically that is triggering the callbacks, You can capture the back button press in your Fragment's Activity and use your own method to handle it:
public class MyActivity extends Activity
{
//...
//Defined in Activity class, so override
#Override
public void onBackPressed()
{
super.onBackPressed();
myFragment.onBackPressed();
}
}
public class MyFragment extends Fragment
{
//Your created method
public void onBackPressed()
{
//Handle any cleanup you don't always want done in the normal lifecycle
}
}
androidx.activity 1.0.0-alpha01 is released and introduces ComponentActivity, a new base class of the existing FragmentActivity and AppCompatActivity.
You can now register an OnBackPressedCallback via addOnBackPressedCallback to receive onBackPressed() callbacks without needing to override the method in your activity.

Categories

Resources