I am having trouble implementing a method to edit the root view of a fragment. Here is the code in question
public class CanvasFragment extends Fragment {
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.canvas_layout, container, false);
return rootView;
}
public void updateColor(String color){
rootView.setBackgroundColor(Color.parseColor(color));
}
My problem arises in conjunction with some code in my main activity:
@Override
public void sendColor(String color) {
FragmentManager fragmentSwitchManager = getFragmentManager();
FragmentTransaction fragmentSwitchTransaction = fragmentSwitchManager.beginTransaction();
CanvasFragment canvasFragment = new CanvasFragment();
fragmentSwitchTransaction.replace(R.id.paletteFrame, canvasFragment);
fragmentSwitchTransaction.addToBackStack(null);
fragmentSwitchTransaction.commit();
canvasFragment.updateColor(color);
}
As you can see, in my main activity I replace a PaletteFragment
within paletteFrame
, a frame layout, with a CanvasFragment
. I have tested this and it works fine, however when attempting to call updateColor()
, I get an error.
The error claims that rootView is a null object reference, and as such, I cannot call setBackgroundColor()
on it. I'm not sure as to why this is the case as I had tested similar code before (In which I did not replace the fragment) and it worked fine. Any help would be appreciated. Thanks!