Show/Hide Fragments and change the visibility attribute programmatically
In FragmentB you're trying get a view which is not on your contentView
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
// this is in fragment_b layout
ListView listView = (ListView) view.findViewById(R.id.listView1);
Button button = (Button) view.findViewById(R.id.button);
/* ... */
// ****************************************
// this is NOT in fragment_b layout, which causes null
// ****************************************
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.fragment_C);
/* ... */
}
Try:
final FrameLayout frameLayout = (FrameLayout) getActivity().getWindow().findViewById(R.id.fragment_C);
Whereas R.id.fragment_C is inflated and setted on MainActivity.
Moreover, I had the same problem until use an extra flag
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
final Fragment fragmentC = new FragmentC();
fragmentTransaction.add(R.id.fragment_C, fragmentC);
fragmentTransaction.commit();
menuIsOn = false;
final View fragmentCView = findViewById(R.id.fragment_C);
final Button btn = (Button) findViewById(R.id.btn);
btnPowers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!menuIsOn) {
fragmentCView.setVisibility(View.VISIBLE);
} else {
fragmentCView.setVisibility(View.INVISIBLE);
}
menuIsOn = !menuIsOn;
}
});