While doing the fragment transaction you might consider setting an id by yourself and later you can retrieve the Fragment
using that id as well.
Here's how you set up and id/tag for your Fragment
which is being launched.
getFragmentManager().beginTransaction().add(R.id.fragment_container, new YourFragment(), "FRAGMENT_1").commit();
Now you can retrieve the Fragment
using the id (i.e. tag) like the following.
getFragmentManager().findFragmentByTag("FRAGMENT_1");
Now to answer your other question, which is how you can access a view component of your Fragment
from your Activity
class, you can do this in multiple ways.
One possible option of doing this is having a BroadcastReceiver
in your Fragment
which can be invoked to update views inside the Fragment
while the broadcast is received from your Activity
. Here's a sample Fragment
with a BroadcastReceiver
to explain the idea behind.
public class YourFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Start listening for the broadcast sent from the Activity
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mYourBroadcastReceiver, new IntentFilter("MESSAGE_FROM_ACTIVITY"));
return inflater.inflate(R.layout.your_fragment_layout, null, true);
}
@Override
public void onDestroyView() {
// The BroadcastReceiver must be destroyed when your Fragment is being destroyed
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mYourBroadcastReceiver);
}
private final BroadcastReceiver mYourBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// This will be invoked when a broadcast is received from your Activity
// Update your views here
}
};
}
Now send the broadcast from your Activity
like this when needed.
Intent intent =new Intent("MESSAGE_FROM_ACTIVITY");
sendBroadcast(i);
Hope that helps!