How to launch a fragment from an activity on button click in Android
Create onClick listener for the button. In the listener method initialize your fragment and use fragmentTransaction to display fragment.
Code to write inside listener method for button:
- FragmentTransaction fragmentTransaction;
- FragmentManager fragmentManager;
- Class fragmentClass=null;
- private Fragment mFragment;
- Notes notes_fragment; // fragment instance of current fragment
- fragmentTransaction = getSupportFragmentManager().beginTransaction();
- mFragment = new CreateNewNote(); // CreateNewNote is fragment you want to display
- fragmentTransaction.replace(R.id.content_fragment, mFragment); // content_fragment is id of FrameLayout(XML file) where fragment will be displayed
- fragmentTransaction.addToBackStack(frag_no); //add fragment to stack
- fragmentTransaction.hide(currentFragment).commit(); // hide current fragment
You may need to do changes in the above code according to your application. O código acima é da minha aplicação onde eu estou usando NavigationDrawer e onClick para cada item do NavigationDrawer correspondente fragmento é exibido.
Se você quiser eu posso carregar este arquivo java em particular..
Espera que ajude...Pergunte se tiver alguma dúvida..
Artigos semelhantes
- How to make the background image of a button disappear when we click it, and make it appear on another button when we click it in Visual Studio
- Why does Android button shape changes but not color after applying background drawable (Android, button, Android drawable, development)?
- How to create my own app, and launch it on Play Store
- Quando é o OnePlus 8T Cyberpunk 2077 Limited Edition Launch?