Encountered a problem in the project, the new development of a tablet app, the project is to put the original mobile app on the left side of the project display, add new features to the right.
First think of fragment, had done some simple demo of fragment, but did not apply to the project, this is a good use of a.
First of all, considering the existing mobile phone app code is very large, and not very standardized (there are about twenty or thirty activity files in the code, and the naming and other aspects are extremely irregular), so I want to not in the original code too much refactoring, after reading an article, slowly have some ideas. (http://mp.weixin.qq.com/s?__biz=MzA3NTYzODYzMg==&mid=404548816&idx=1&sn= F042037982ed2e74210c57edf864e31a&scene=0#wechat_redirect) This article also said some of the problems of refactoring, but after looking at it is not suitable for their own, but very good for themselves to provide a way of thinking. So I wrote a demo.
The structure of the demo is like this
I first wrote a basepadfragment, so that all the fragment to implement this base class, and thus unify the implementation of some common methods. Because it is a demo, the base class only provides a fragment jump method
Basepadfragment.java
Importandroid.app.Fragment;ImportAndroid.app.FragmentManager;Importandroid.app.FragmentTransaction;ImportAndroid.content.Context;ImportAndroid.os.Bundle;Importandroid.support.v4.app.FragmentActivity;Importjava.util.List;/*** Created by Bob on 2016/4/11.*/ Public classBasepadfragmentextendsfragment{ PublicContext Mcontext; Public voidStarttofragment (Context context,intcontainer,fragment newfragment) {Fragmentmanager Manager=Getfragmentmanager (); Fragmenttransaction Transaction=manager.begintransaction (); Transaction.replace (container,newfragment); Transaction.addtobackstack (Context.getclass (). GetName ()); Transaction.commit (); }}
The parameters in the method are context: Context, Container:fragment container, Newfragment: The object to jump to fragment;
Then look inside the method body, first get some of the main objects of Frament fragmentmanager/fragmenttransaction and then use transaction for fragment replacement, It is critical that the current fragment be pressed again, as the return button cannot be returned to the previous fragment if it is not added. Finally, commit the commit method.
The main interface activity is relatively simple is a simple oncreatview in the back of the source can be viewed.
Again, the layout of the main interface:
Activity_index.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" Match_parent "android:baselinealigned=" false " > <framelayout android:id= "@+id/layout_container" android:layout_width= "0DP" Android:layout_ height= "Match_parent" android:layout_weight= "4" > <fragment android:id= "@+id/left_fragment" Android:name= "Com.sailing.www.multiscreendemo.fragment.LeftFragment" android:layout_width= "Match_par Ent "android:layout_height=" match_parent "/> </FrameLayout> <view android:layout_width = "5DP" android:layout_height= "match_parent" android:background= "#000000"/> <framelayout and Roid:layout_width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "6" > <fragme NT Android:id= "@+id/righT_fragment "Android:name=" Com.sailing.www.multiscreendemo.fragment.RightFragment "Android:layout_wid Th= "Match_parent" android:layout_height= "match_parent"/> </FrameLayout></LinearLayout>
You can see that I added two fragment to the main interface, and put the two fragment levels in a linearlayout. When put in the time to remember to wrap the fragment outside a layer of Parentview I use is framelayout, because in the jump to container for the jump, So in this parentview is equivalent to a container to put fragment inside, all the pages are replaced in this container to operate. And this container must add ID, otherwise it will not find the view error.
The interface effect is like this.
Fragment on the left
Leftframgment:
Import Android.app.fragment;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.os.persistablebundle;import Android.support.annotation.nullable;import Android.support.v4.app.fragmentactivity;import Android.support.v7.widget.linearlayoutmanager;import Android.support.v7.widget.recyclerview;import Android.view.layoutinflater;import Android.view.View;import Android.view.viewgroup;import Android.widget.button;import Android.widget.listview;import Android.widget.TextView ;/** * Created by Bob on 2016/4/5. */public class Leftfragment extends Basepadfragment implements view.onclicklistener{private Button Btnnextpage,btnnext another; Private Recyclerview Mrecyclerview; Private Horizontallistadapter Horizontallistadapter; @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {Vi EW view = inflater.inflate (R.layout.layout_left, NULL); Btnnextpage = (ButtON) View.findviewbyid (r.id.btn_next_page); Btnnextanother = (Button) View.findviewbyid (R.id.btn_next_another); Btnnextpage.setonclicklistener (this); Btnnextanother.setonclicklistener (this); Mrecyclerview = (Recyclerview) View.findviewbyid (R.id.recycler_view); Linearlayoutmanager LayoutManager = new Linearlayoutmanager (getactivity ()); Layoutmanager.setorientation (linearlayoutmanager.horizontal); Set Layout manager Mrecyclerview.setlayoutmanager (LayoutManager); string[] DataSet = new string[100]; for (int i = 0; i < dataset.length; i++) {Dataset[i] = "item" + I; } recycleradapter Madapter = new Recycleradapter (dataset); Mrecyclerview.setadapter (Madapter); return view; } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_next_page: Anotherfragment anotherfragment = new Anotherfragment (); Starttofragment (LGTivity (), R.id.layout_container, anotherfragment); Break Case R.id.btn_next_another:nextanotherfragment nextanotherfragment = new Nextanotherfragment (); Starttofragment (Getactivity (), r.id.layout_container,nextanotherfragment); Break Default:break; }} public class Recycleradapter extends recyclerview.adapter<recycleradapter.viewholder> {private Str Ing[] Mdataset; Public Recycleradapter (string[] DataSet) {mdataset = DataSet; } public class Viewholder extends Recyclerview.viewholder {public TextView mtextview; Public Viewholder (View Itemview) {super (Itemview); Mtextview = (TextView) Itemview; }} @Override public int getitemcount () {return mdataset.length; } android.support.v7.widget.RecyclerView.AdApter#onbindviewholder (android.support.v7.widget.RecyclerView.ViewHolder, * int) */@Override public void Onbindviewholder (viewholder holder, int position) {Holder.mTextView.setText (Mdataset[positi On]); } android.support.v7.widget.recyclerview.adapter#oncreateviewholder (android.view.ViewGroup, * int) */@Override public Viewholder Oncreateviewholder (viewgroup parent, int viewtype) {View view = View.inflate (Parent.getcontext (), Android. R.layout.simple_list_item_1, NULL); Viewholder holder = new Viewholder (view); return holder; } }}
Because there are some other tests in this demo, there are some miscellaneous controls inside. We only look at the main module of the code, that is, the operation of the button, after clicking on the button I jump to another framgment, directly with the parent class Starttofragment () method, operation is still very simple.
On the second page I have passed and fetched the parameters here.
Anotherfragment:
Import Android.app.fragment;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.support.annotation.nullable;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.arrayadapter;import Android.widget.Button; Import Android.widget.edittext;import android.widget.spinner;/** * Created by Bob on 2016/4/5. */public class Anotherfragment extends Basepadfragment implements View.onclicklistener {private Button btntothirdpage; Private EditText Medtname; Private Spinner Mspintext; @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {Vi EW view = inflater.inflate (R.layout.layout_another, NULL); Mcontext = Getactivity (); Btntothirdpage = (Button) View.findviewbyid (R.id.btn_another); Medtname = (EditText) View.findviewbyid (r.id.edt_name); Mspintext = (Spinner) View.findviewbyid (r.iD.spi_text); String [] Textarray = Getresources (). Getstringarray (R.array.text); arrayadapter<string> textadapter = new arrayadapter<string> (Mcontext,r.layout.myspinner,textarray); Textadapter.setdropdownviewresource (Android. R.layout.simple_spinner_dropdown_item); Mspintext.setadapter (Textadapter); Btntothirdpage.setonclicklistener (this); return view; } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_another: Thirdfragment thirdfragment = new Thirdfragment (); String name = Medtname.gettext (). toString (); Bundle bundle = new bundle (); if (name = null) {bundle.putstring ("name", name); } bundle.putstring ("Password", "12345678"); Thirdfragment.setarguments (bundle); Starttofragment (Getactivity (), R.id.layout_container, thirdfragment); BrEak Default:break; } }}
Also in the button click event, I use bundles for data transfer, it is very simple to use. The third interface for data acquisition is also very simple.
Thirdfragment:
Import Android.app.fragment;import Android.os.bundle;import Android.support.annotation.nullable;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.TextView ;/** * Created by Bob on 2016/4/11. */public class Thirdfragment extends Fragment { private TextView tvname; @Nullable @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedinstancestate) { View view = inflater.inflate (r.layout.layout_third_fragment, null); Tvname = (TextView) View.findviewbyid (r.id.tv_name); Bundle Bundle = Getarguments (); String name =bundle.getstring ("name"); String Password = bundle.getstring ("password"); if (null! = name) { Tvname.settext (name+ " " +password); } return view;} }
Simple idea, but in the reference to the project inside to find a more curious question, that is, despite the fragment jump, but the last fragment seems to have not been covered, This means that the current fragment can also operate on a fragment. This is a bit of a pit dad, after looking for a lot of information after finally to solve the problem. The following is the final Basepadfragment starttofragment method.
/** * Jump to another fragment method * @param currentfragment Current fragment * @param co Ntainer: Current Fragment container * @param newfragment Next Fragment * */public void starttofragment (Fragment currentfragm Ent,context context,int container,fragment newfragment) {if (currentfragment! = newfragment) {manager = G Etfragmentmanager (); Transaction = Manager.begintransaction (); if (! newfragment.isadded ()) {transaction.hide (currentfragment). Add (Container,newfragment); Transaction.addtobackstack (Context.getclass (). GetName ()); Transaction.commit (); }else{transaction.hide (currentfragment). Show (Newfragment); Transaction.addtobackstack (Context.getclass (). GetName ()); Transaction.commit (); } } }
This will be a good deal with the last fragment can not be covered by the problem. The logic of processing is this, first determine whether the new fragment is added if not, hide the above fragment, and then the new fragmentadd come in, if add came in directly hide off the previous fragment, directly press the stack and submit.
Source Address: Https://github.com/bobLion/MultiScreenDemo
Android Fragment for split screen