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. Il codice di cui sopra viene dalla mia applicazione dove sto usando NavigationDrawer e onClick per ogni elemento di NavigationDrawer viene visualizzato il frammento corrispondente.
Se vuoi posso caricare questo particolare file java..
Spero che aiuti..Chiedi se hai qualche dubbio..
Articoli simili
- 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)?
- Why do we use Android support injection in our fragment?
- How to create my own app, and launch it on Play Store