Reputation: 62
I've done everything I can find to fix my problem, it's the same as many others with the fragmentmanager that can't find a view.
Tried everything I have found online and could think about.
Heres my MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MenuFragment menuFragment = new MenuFragment();
FragmentManager fmStart = getSupportFragmentManager();
FragmentTransaction fmTrans = fmStart.beginTransaction();
fmTrans.add(R.id.fragmentContainerID, menuFragment);
fmTrans.commitAllowingStateLoss();
}
public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.fragmentContainerID, fragment, tag);
ft.commitAllowingStateLoss();
}
}
The error I get is the same as many others:
java.lang.IllegalArgumentException: No view found for id 0x7f080073 (se.iteda.hangman:id/fragmentContainerID) for fragment MenuFragment{d8a58aa (60d879ee-e84c-425e-a1a1-8e9be9c3b3a8) id=0x7f080073}
What I want to do is load a fragment at the start (MenuFragment) and in that fragment, I have 2 buttons that change fragments.
Upvotes: 0
Views: 13190
Reputation: 18677
Ok. I opened your project in Github.
Error is here:
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
....
fmTrans.add(R.id.fragmentContainerID, menuFragment);
....
}
You are adding the fragment into fragmentContainerID
. However, that view was not added to the Activity
(leading to the view not found error).
So, in order to fix, I think you just need to apply the layout to the main activity. Something like:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this after super.onCreate()
setContentView(R.layout.activity_main);
.....
}
EDIT
And as I said in one of my comments, I think you don't need the code below at MenuFragment.java. I think you can remove it.
MenuFragment menuFragment = new MenuFragment();
((MainActivity)getActivity()).addFragment(menuFragment, true, "Menu");
Upvotes: 7