This time I share is to imitate the Android app this type, as well as NetEase news, they are very similar to the menu interface.
I am using the app bar advocated in material design. With Toolbar+drawerlayout+fragment implementation, you can also nest inside the fragment Viewpager so that fragment contains a viewpager, Viewpager contains more faragment to display the content.
The approximate function of this demo is described:
Using toolbar, then there will be a left menu, using the fragment to implement, and then click on the menu will show a different fragment, and the fragment will not hide the toolbar, Do not use a new activity for every click, as in the previous case, and then cover up the toolbar, and you can go and see the blog:
Imitation knows app one . 、
The main idea:
Some of the details of the use of toolbar is the need to inherit appcompatactivity (V7 package), the use of toolbar is also under the V7 package, then the environment is not detailed here, and then need to re-write a style apptheme, Remove the default Actionbar. Then in the layout file Head use toolbar, and then in the use of a drawerlayout, his first view is the content area, we use a framelayout, the second view is the left menu, we also use a framelayout, so, We can reuse the content area and use different fragment to place it in the second content area.
Specific or open the code to achieve it:
Project structure:
It contains 3 fragment to show the content area, a mainactivity, and then a leftfragment and corresponding adapter
Look at the layout file first:
The main layout file, like above, there's nothing to talk about.
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "xmlns:app=" Http://schemas.android.com/apk/res/com.example.mytoolbar_04 "Android: Layout_width= "Match_parent" android:layout_height= "match_parent" android:background= "#ffffff" android:orientation = "vertical" tools:context= "com.example.mytoolbar_04.MainActivity" > <android.support.v7.widget.toolbar Android:id= "@+id/id_toolbar" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:background= "? attr/colorprimary" android:minheight= "? Attr/actionbarsize" app:navigationicon= "@drawab LE/IC_TOC_WHITE_24DP "App:popuptheme=" @style/themeoverlay.appcompat.light "app:theme=" @style/themeoverlay.ap Pcompat.actionbar "app:title=" app title "/> <android.support.v4.widget.drawerlayout android:id=" @+i D/id_drawerlayout "Android:layout_width=" Match_paRent "android:layout_height=" match_parent "> <framelayout android:id=" @+id/id_content_conta Iner "android:layout_width=" match_parent "android:layout_height=" match_parent "> </fram elayout> <framelayout android:id= "@+id/id_left_menu_container" Android:layout_width= "Ma Tch_parent "android:layout_height=" match_parent "android:layout_gravity=" left "Android:ba ckground= "#ffffff" > </FrameLayout> </android.support.v4.widget.drawerlayout></linearlayout> ;
Then is the left menu of the ListView layout file, a picture + text as an item, and so on
<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" 48DP " android:gravity=" Center_ Vertical " android:paddingright=" 16DP " > <imageview android:layout_marginleft=" 16DP " Android:id= "@+id/id_item_icon" android:src= "@drawable/music_36px" android:layout_marginright= "8DP" android:layout_gravity= "center_vertical" android:layout_width= "wrap_content" android:layout_ height= "Wrap_content"/><textview android:id= "@+id/id_item_title" android:layout_marginleft= " 72DP " android:layout_width=" wrap_content " android:layout_height=" Wrap_content " android: Textcolor= "#64000000" android:textsize= "16sp" android:text= "@string/hello_world" android:layout _gravity= "Center_vertical"/></framelayout>
Then the style file:
He is the application reference in the manifest file, his theme needs to be android:Theme.Light, and then add the package with VALUES-V14, it also needs to change the style file, otherwise it may be wrong
<resources> <style name= "Appbasetheme" parent= "Android:Theme.Light" > </style> < Style name= "Apptheme" parent= "Theme.AppCompat.Light.NoActionBar" > <item name= "colorprimary" > @color/ material_blue_500</item> <item name= "Colorprimarydark" > @color/material_blue_700</item> <item name= "coloraccent" > @color/material_green_a200</item> </style></resources >
Toolbar on the menu:
<menu xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/ Tools "xmlns:app=" Http://schemas.android.com/apk/res-auto "tools:context=" com.example.mytoolbar_04.MainActivity " > <!--always show-<item android:id= "@+id/id_action_refreash" android:icon= "@drawable/ic_cach ED_WHITE_24DP "android:orderincategory=" "android:title=" @string/action_refreash "app:showasaction = "Always"/> <!--is usually displayed-<item android:id= "@+id/id_action_delete" android:icon= "@drawab LE/IC_DELETE_WHITE_24DP "android:orderincategory=" "android:title=" @string/action_delete "app:show asaction=/> <!--always show-<item android:id= "@+id/id_action_favorite" android:icon= "@drawable/ic_favorite_outline_white_24dp" android:orderincategory= "android:title=" @string/action_favor Ite "app:showasaction=" Always "/> <!--not displayed on Actionbar-<item android:id= "@+id/action_settings" android:orderincategory= "Android:showasaction=" "Never" android:title= "@string/action_settings"/></menu>
About the color of those who go to configure the good, like the color on the line, the following are the plays:
First of all, the content area, my three fragment are all similar, so just post one, he shows a TextView
Import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.linearlayout;import Android.widget.linearlayout.layoutparams;import Android.widget.textview;public class FirstFragment extends Fragment {@Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {TextView TV = new TextView (getactivity ()); Linearlayout.layoutparams LP = new Layoutparams (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); tv.setlayoutparams (LP); Tv.settextsize, Tv.settext ("First fragment"); return TV;}}
And then Menuitem.java, his domain class, is a collection of some properties of the item on the right-hand menu
Public MenuItem (String text, boolean isSelected, int icon, int iconselected) {this.text = text;//text displayed this.isselected = is Selected; Whether it is selected This.icon = icon; His icon this.iconselected = iconselected; The selected icon}boolean isSelected; String text;int icon;int iconselected;}
Then there is the Leftmenufragment.java class, which is the menu on the left to fill the second view in the Drawerlayout. He inherits Listfragment, does not need to rewrite the Oncreateview method, listens to his item's Click events, uses an interface onmenuitemselectedlistener to be responsible for interacting with the activity, and then, It contains a method Menuitemselecte (String title, int position), respectively the title of item and his position in the ListView position
Import Android.os.bundle;import Android.support.annotation.nullable;import android.support.v4.app.ListFragment; Import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.listview;public class Leftmenufragment extends listfragment{private static final int size_menu_item = 3;/ /total number of menus private menuitem[] Mitems = new Menuitem[size_menu_item];p rivate leftmenuadapter madapter; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); MenuItem MenuItem = null;for (int i = 0; i < Size_menu_item; i++) {MenuItem = new MenuItem (Getresources (). Getstringarray (R.array.array_left_menu) [i], false, r.drawable.music_36px, r.drawable.music_36px_light); mitems[i] = MenuItem;}} @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {return Super.oncreateview (Inflater, container, savedinstancestate);} @Overridepublic void onviewcreated (view view, @Nullable Bundle SavedinstaNcestate) {super.onviewcreated (view, savedinstancestate); Setlistadapter (madapter = new Leftmenuadapter (getActivity ( ), Mitems));} @Overridepublic void Onlistitemclick (ListView l, View v, int position, long id) {Super.onlistitemclick (L, V, position, id); if (Mmenuitemselectedlistener! = null) {mmenuitemselectedlistener.menuitemselected (((MenuItem) Getlistadapter (). GetItem (position)). text, position);//Click events, pass parameters to activity processing}madapter.setselected (position);} Click Listener public Interface onmenuitemselectedlistener{/** * @param title is clicked on the title of the ListView * @param position is clicked on the ListView posit Ion */void menuitemselected (String title, int position);} Private Onmenuitemselectedlistener Mmenuitemselectedlistener; Listen to what happens after the ListView is clicked to interact with the activity public void Setonmenuitemselectedlistener (Onmenuitemselectedlistener Menuitemselectedlistener) {this.mmenuitemselectedlistener = Menuitemselectedlistener;}}His adapter: The adapter does not say much, mainly there is a setselected method, his role is to go to set the clicked item of some background, icon
Import Android.content.context;import Android.graphics.color;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.arrayadapter;import Android.widget.imageview;import Android.widget.textview;public class Leftmenuadapter extends ArrayAdapter< menuitem>{private layoutinflater minflater;private int mselected;public leftmenuadapter (context context, MenuItem[ ] {objects) {Super (context,-1, objects); minflater = Layoutinflater.from (context);} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {if (Convertview = = null) {Convertview = MInf Later.inflate (R.layout.item_left_menu, parent, false);} ImageView IV = (ImageView) Convertview.findviewbyid (R.id.id_item_icon); TextView title = (TextView) Convertview.findviewbyid (r.id.id_item_title); Title.settext (GetItem (position). text); Iv.setimageresource (GetItem (position). Icon) Convertview.setbackgroundcolor (color.transparent);//If it is the current item, is to set him to the corresponding backgroundcolor and the new Drawable to differentiate between other if (position = = mselected) {Iv.setimageresource (GetItem (position). iconselected); Convertview.setbackgroundcolor (GetContext (). Getresources (). GetColor (r.color.state_menu_item_selected));} return Convertview;} /** * @param position click on the location of item */public void setselected (int position) {this.mselected = position; Notifydatasetchanged ();}}Then, is our most important mainactivity, there are comments, should be able to understand ~ ~, some of his functions, initialize the Ui,toolbar, and then need to select the first title and fragment to be displayed in the OnCreate method, Then note that the caption displayed on the toolbar should be the same as the title of the item that the ListView clicked on. Then click on the event premise is the current leftmenufragment is expanded, click after you need to first hide all the fragment, then to determine the fragment need to display and then to display. Then handle the Click event of the toolbar menu, where a toast will be displayed after clicking. The behavior that should be done when the physical return key is pressed, when the menu is expanded to close the menu instead of closing the app, then the app is closed without a menu expansion.
Import Android.os.bundle;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmenttransaction;import Android.support.v4.widget.drawerlayout;import Android.support.v7.app.actionbardrawertoggle;import Android.support.v7.app.appcompatactivity;import Android.support.v7.widget.toolbar;import Android.text.textutils;import Android.view.gravity;import Android.view.keyevent;import Android.view.menu;import Android.view.view;import Android.widget.Toast;import Com.example.mytoolbar_04.fragment. Firstfragment;import com.example.mytoolbar_04.fragment. Secondfragment;import com.example.mytoolbar_04.fragment. Thirdfragment;public class Mainactivity extends Appcompatactivity{private actionbardrawertoggle Mactionbardrawertoggle;private drawerlayout mdrawerlayout;//includes left menu and content area private Toolbar mtoolbar;//toolbarprivate Leftmenufragment mleftmenufragment;//left Menu private String mtitle;private boolean flag = false;//left menu expanded flag private Static final String Key_titlle = "Key_title";p RivAte firstfragment firstfragment; Corresponds to three different content areas, the first private secondfragment secondfragment;//the second private thirdfragment thirdfragment;// A third @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Inittoolbar (); Initviews ();//Reset the page is the toolbar title restoretitle (savedinstancestate); Fragmentmanager fm = Getsupportfragmentmanager ();//v4 Package mleftmenufragment = (leftmenufragment) Fm.findfragmentbyid ( R.id.id_left_menu_container); if (mleftmenufragment = = null) {mleftmenufragment = new leftmenufragment (); Fm.begintransaction (). Add (R.id.id_left_menu_container, mleftmenufragment). commit ();} To Leftfragment Click event Monitoring, Need is at this time leftfragment is expanded,//and then click Finish need to close the leftmenufragment, Displays the fragmentmleftmenufragment of the item that was clicked. Setonmenuitemselectedlistener (New Leftmenufragment.onmenuitemselectedlistener () {@Override public void menuitemselected (String title, int position ) {showselectedfragment (position); mtitle = Title;mtoolbar.settItle (mtitle);//Set toolbar text mdrawerlayout.closedrawer (gravity.left); Close menu});//Set default fragmentshowselectedfragment (0);} /** * When clicking Leftfragment, select what you want to display fragment * @param position */protected void showselectedfragment (int position) { Fragmentmanager fm = Getsupportfragmentmanager (); Fragmenttransaction fragmenttransaction = Fm.begintransaction (); hidefragment (fragmenttransaction); switch (position {case 0:if (firstfragment = = null) {firstfragment = new firstfragment (); Fragmenttransaction.add (R.id.id_content_ container, firstfragment);} Else{fragmenttransaction.show (firstfragment);} Break;case 1:if (secondfragment = = null) {secondfragment = new secondfragment (); Fragmenttransaction.add (R.id.id_ Content_container, secondfragment);} Else{fragmenttransaction.show (secondfragment);} Break;case 2:if (thirdfragment = = null) {thirdfragment = new thirdfragment (); Fragmenttransaction.add (R.id.id_content_ container, thirdfragment);} Else{fragmenttransaction.show (thirdfragment);} break;} Fragmenttransaction.cOmmit ();} /** * Every time you show fragment, go ahead and hide fragment * @param fragmenttransaction */protected void Hidefragment (fragmenttransaction Fragmenttransaction) {if (firstfragment! = null) {fragmenttransaction.hide (firstfragment);} if (secondfragment! = null) {fragmenttransaction.hide (secondfragment);} if (thirdfragment! = null) {fragmenttransaction.hide (thirdfragment);}} /** * Restores the title so that the text in the toolbar is the same as the ListView text on the leftmenufragment * @param savedinstancestate */private void Restoretitle (Bundle Savedinstancestate) {if (savedinstancestate! = NULL)//exists when the title is read out, showing mtitle = Savedinstancestate.getstring (key_ Titlle); if (Textutils.isempty (mtitle))//How does not exist, like the first click to apply, the display Main Page {mtitle = Getresources (). Getstringarray ( R.array.array_left_menu) [0];} Mtoolbar.settitle (mtitle);} /* * This method execution period for the user to click the Home button for a long time did not return to the main interface or to switch vertical screen, * This time will be saved for the fragment title, download by OnCreate method used to need to rewrite, Or there may be overlapping of text (due to fragment overlap) */@Overrideprotected void onsaveinstancestate (Bundle outstate) { Super.onsaveinstancestate (outstate); Outstate.putstring (Key_titlle, MTiTLE);} /** * Initialize Toolbar */private void Inittoolbar () {Toolbar Toolbar = Mtoolbar = (Toolbar) Findviewbyid (R.id.id_toolbar); Toolba R.settitle (Getresources (). Getstringarray (R.array.array_left_menu) [0]); Setsupportactionbar (toolbar);// Toolbar.setonmenuitemclicklistener (New Toolbar.onmenuitemclicklistener () {@Overridepublic Boolean is required after the title is set Onmenuitemclick (Android.view.MenuItem arg0) {int event = Arg0.getitemid (); switch (event) {case R.id.id_action_refreash : Showtoast ("You clicked the Refresh button"), Return true;case r.id.id_action_delete:showtoast ("You clicked the Delete button"); return true;case r.id.id_ Action_favorite:showtoast ("You clicked on the Favorites button"); return true;} return false;}}); /** * Print Toast * @param text needs to be displayed */protected void Showtoast (String text) {Toast.maketext (Getapplicationcontext (), text, Toast.length_short). Show ();} /* * Create Menu */@Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return Super.oncreateoptionsmenu (menu);} /** * Initialize */private void Initviews () {mdrawerlayout = (drawerlayoUT) Findviewbyid (r.id.id_drawerlayout);//This drawerlistener needs to monitor the unfolding state of drawer and change his flagmactionbardrawertoggle = new Actionbardrawertoggle (This, mdrawerlayout, Mtoolbar, R.string.open, r.string.close) {@Overridepublic void ondrawerclosed (View drawerview) {super.ondrawerclosed (drawerview); flag = false;} @Overridepublic void ondraweropened (View drawerview) {super.ondraweropened (drawerview); flag = True;}}; Mactionbardrawertoggle.syncstate (); Mdrawerlayout.setdrawerlistener (Mactionbardrawertoggle);} /* * One of his functions is to listen to whether the current left-hand menu is expanded, or, if expanded, to close without exiting the app, otherwise close the app */@Overridepublic boolean onKeyDown (int keycode, keyevent event) {if ( Flag) {mdrawerlayout.closedrawers (); return true;} Return Super.onkeydown (KeyCode, event);}}Results:
Refer to Bolg,hyman: Android 5.x Theme and ToolBar combat
Imitating Android App II