Skip to content Skip to sidebar Skip to footer

Accessing A List From A Different Fragment

So I have my MainActivity.java, I also have a FragmentA.java and a FragmentB.java. In my MainActivity I have a BottomNavigation which allows me to switch between the two fragments.

Solution 1:

You could achieve this by two ways:

1) Through Interface Contract between the Fragment and Activity

classFragmentA: Fragment() {
    interfaceSomeInterfaceName{
        funsetSelectedItem(item: SomeItem)
    }
}

classFragmentA: Fragment() {
    interfaceAnotherInterfaceName{
        fungetSelectedItem(): SomeItem
    }
}

classContainerActivity: Activity(), AnotherInterfaceName, SomeInterfaceName {
   var someItem: SomeItem? = nullfunsetSelectedItem(item: SomeItem) {
        someItem = item
        // inflate your FragmentB
    }     

    fungetSelectedItem(): SomeItem {
        return someItem;
    }
}

But the best solution in my opinion is to use a shared ViewModel for this case.

You can read about this he here under "Share data between fragments" section.

Solution 2:

Doing the job by interface is correct, But you have to bind it to the Fragment in the onAttached lifeCycle method.

Define an Interface. OnFragmentInteractionListener.java

publicinterfaceOnFragmentInteractionListener {
    // TODO: Update argument type and namevoidonFragmentInteraction(String args);
}

Then Implement your activity with the interface.

publicclassMainActivityextendsActionBarActivityimplementsOnFragmentInteractionListener{

        @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }

        @OverrideonFragmentInteraction(String args){
            **// Made the Change Here**// Send Local Broadcast Receiver Intent intent = newIntent("UPDATE_LIST");
            intent.putExtra("TYPE", 0);
            // Change the args to get position or the relevant param
            intent.putExtra("POSITION", selectedPosition);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
   }

In the FragmentA.java,

publicclassFragmentAextendsFragment {
    OnFragmentInteractionListener mCallback;

    @OverridepublicvoidonAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented// the callback interface. If not, it throws an exceptiontry {
            mCallback = (OnFragmentInteractionListener) context;
        } catch (ClassCastException e) {
            thrownewClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    ...

    adapter.setOnItemClickListener(newRewardItemAdapter.OnItemClickListener() 
    {
       @OverridepublicvoidonItemClick(int position) {
       //When I click the item, pass theItem to FragmentBCustomObjecttheItem= items.get(position);
            // Send the selected Item Name to Main Activity through args
            mCallback.onFragmentInteraction(theItem.getName);
       }
    });

}

On your FragmentB.java class add Local Broadcast Receiver

public class FragmentBt extends Fragment{

publicstaticFragmentnewInstance(){
       ...
    }

    @Nullable@OverridepublicViewonCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.layout, container, false);
        return v;
    }

    ...

    @OverridepublicvoidonViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // Register Local Broadcast ReceiverLocalBroadcastManager.getInstance(getContext()).registerReceiver(mMessageReceiver, newIntentFilter("UPDATE_LIST"));
    }

    @OverridepublicvoidonDestroy() {
        super.onDestroy();
        // Destroy the  Local Broadcast ReceiverLocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mMessageReceiver);
    }

    // Create Broadcast Receiver instanceprivateBroadcastReceiver mMessageReceiver = newBroadcastReceiver() {
        @OverridepublicvoidonReceive(Context context, Intent intent) {
            if(intent.hasExtra("POSITION")){
                mAdapter.notifyItemChanged(intent.getIntExtra("POSITION", 0));
                // Update Adapter as the requirement
            }
        }
    };

}

Hope this will help. Cheers!!

Post a Comment for "Accessing A List From A Different Fragment"