Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android pass value from child fragment back to parent fragment

I was having some problem when trying to get the value from fragment upon dismiss. My fragment A will open up fragment B, when the button in fragment B is clicked, I wanted to get a value and pass back to fragment A to be displayed. However, I am not sure how to do it.

Fragment A:

@Click(R.id.buttonAttach)
void buttonAttachClicked(View v){
        SupportAttachFileFragment fragment = new SupportAttachFileFragment_();
        fragment.show(getFragmentManager(), null);

        // get value here and display
        textViewLogCounter.setText();
    }
}

Fragment B:

When this button onClicked, I wanted to pass the value back to fragment A and display.

@Click(R.id.buttonAttach)
void buttonAttachClicked(View v){
    System.out.println("TOTAL " + selectedRows.size());
    dismiss();
}

I not sure how to do it. I was thinking of Bundle but Bundle is to pass parameter to a new activity. In this case, my fragment is already opened but I wanted to pass some values back.

Any ideas? Thanks!

like image 532
BlackMamba Avatar asked Jul 06 '18 05:07

BlackMamba


People also ask

How you can pass the data from one fragment to another fragment?

So to share a string between fragments you can declare a static String in Activity. Access that string from Fragment A to set the value and Get the string value in fragment B. 2. Both fragments are hosted by different Activities- Then you can use putExtra to pass a string from Fragment A of Activity A to Activity B.

How do you pass data between fragments in Kotlin?

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.


1 Answers

You can use shared ViewModel. Create ViewModel in activity scope and it will be available for activity and all of its fragment.

MyViewModel sharedViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel::class.java)

Then observe your desire data of sharedViewModel. If you change data of sharedViewModel in any fragment or activity it will be changed for all fragment and activity. See below image or read doc.

enter image description here

like image 52
Shalauddin Ahamad Shuza Avatar answered Sep 27 '22 17:09

Shalauddin Ahamad Shuza