Hello I just want to switch from a fragment to another using a button. Nothing difficult... the code works well but I have spent a lot of time because Android goesto error if I hook frameLayout with autocompile. I'm explaining better:
package com.example.fragcookbook;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity {
FragmentOne mFragmentOne;
FragmentTwo mFragmentTwo;
int showingFragment=0;
@Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
mFragmentOne = new FragmentOne();
mFragmentTwo = new FragmentTwo();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frameLayout, mFragmentOne);
fragmentTransaction.commit();
showingFragment=1;
}
public void switchFragment(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (showingFragment==1) {
fragmentTransaction.replace(R.id.frameLayout, mFragmentTwo);
showingFragment = 2;
} else {
fragmentTransaction.replace(R.id.frameLayout, mFragmentOne);
showingFragment=1;
}
fragmentTransaction.commit();
}
In all rows where you see R.id.frameLayout i have to handly write frameLayout..... Android colors it red but It works...
But if i choose the resource with autocompile...
...when i run app Android gives me this error....
Why? is not best practice use autocompile? Thanks in advance
Try this may will help you.Go to "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.
Or
Restar you android studio and emulator