Issue
I in my app i have a fragment that contains some input fields, i show this fragment in two different activities, in both cases, the layout will be the same but I need to perform different actions based on who is the parent activity.
I'll try to explain better my problem and the solution that I'm using with the following code:
ActivityA
public class ActivityA extends AppCompatActivity{
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ActivityA);
navController = Navigation.findNavController(this,R.id.graphA);
initView();
}
public void nextFragment(int actionID, Bundle bundle) {
btn.setOnClickListener(v->{
navController.navigate(from_activityA_toFragment, bundle);
});
}
ActivityB
public class ActivityB extends AppCompatActivity{
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ActivityA);
navController = Navigation.findNavController(this,R.id.graphB);
initView();
}
public void nextFragment(int actionID, Bundle bundle) {
btn.setOnClickListener(v->{
navController.navigate(from_activityB_toFragment, bundle);
});
}
In my fragment class now i have something like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragemnt, container, false);
if(getActivity().getClass().equals(ActivityA.class))
//Do things of activityA
else if(getActivity().getClass().equals(ActivityB.class)))
//Do things of activityB
return rootview;
}
Now this code work but doesn't seem the best way to archive my goal so have anyone some suggestion? Thanks
Solution
The correct way to do it is to define an interface in the Fragment, make the Activity implement the interface, and make the Fragment cast the Activity to the interface.
The following guide describes it: https://web.archive.org/web/20180405192526/https://developer.android.com/training/basics/fragments/communicating.html
public class HeadlinesFragment extends Fragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@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 = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
Answered By - EpicPandaForce