In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the example analysis of Android code quality management. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Template method-Base Class Encapsulation
Activity and Fragment should be the most commonly used components of Android, and a simple encapsulation of them is also of great help to improve the simplicity of the code.
BaseActivity:
Public abstract class BaseActivity extends FragmentActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); init (); findViews (); initData (); setListener (); setting () } / * * get context * @ return Context * / public Context getContext () {return this;} / * initialization parameter * / public abstract void init () / * find all controls * / public abstract void findViews (); / * initialize page data * / public abstract void initData (); / * set the control's listening event * / public abstract void setListener () / * subsequent parameter settings * / public abstract void setting ();}
BaseFragment:
Public abstract class BaseFragment extends Fragment {@ Override public void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState);} @ Override public void onStart () {super.onStart (); init (); findViews (); initData (); setListener () Setting ();} public Context getContext () {return getActivity ();} public abstract void init (); public abstract void findViews (); public abstract void initData (); public abstract void setListener (); public abstract void setting ();}
The code is relatively simple, using the template design pattern, a method only does one thing, initialization only does initialization operation, setting listener only sets listener. No matter how many Activity\ Fragment can unify the coding style, it looks clearer and more uncluttered.
Fragment simple Management
Let's first take a look at the standard creation and management of Fragment
Private void showFragment () {FragmentTransaction fragmentTransaction = getSupportFragmentManager (). BeginTransaction (); hideFragment (fragmentTransaction); if (mFragment1== null) {mFragment1= new MyFragment1 (context); fragmentTransaction.add (R.id.content, mFragment1); fragmentTransaction.commit ();} else {fragmentTransaction.show (mFragment1); fragmentTransaction.commit ();}}
Copy this method every time you create a Fragment. The code is redundant and is not good for maintenance and update.
Let's package it.
Public class FragmentFactory {private FragmentActivity mContext; private static FragmentFactory factory = new FragmentFactory (); / / used to store the created Fragment object private Map mFragmentMap=new HashMap (); private int mLayoutId; private FragmentFactory () {} public static FragmentFactory getInstance () {return factory;} / / layoutId id public FragmentFactory init (FragmentActivity context,int layoutId) {this.mContext = context; this.mLayoutId=layoutId; return factory;} public Activity getParentActivity () {return mContext } private Fragment createFragment (Class clazz) {Fragment fragment = null; try {fragment = getFragment (clazz.getName ()); FragmentTransaction fragmentTransaction = mContext.getSupportFragmentManager (). BeginTransaction (); hideFragment (fragmentTransaction); if (fragment = = null) {fragment = (Fragment) clazz.newInstance (); setFragment (fragment); fragmentTransaction.add (mLayoutId, fragment); fragmentTransaction.commit ();} else {fragmentTransaction.show (fragment); fragmentTransaction.commit () } catch (InstantiationException e) {e.printStackTrace ();} catch (IllegalAccessException e) {e.printStackTrace ();} return fragment;} private Fragment getFragment (String className) {Fragment fragment = mFragmentMap.get (className); return fragment;} private void setFragment (Fragment fragment) throws InstantiationException, IllegalAccessException {String className = fragment.getClass (). GetName (); mFragmentMap.put (className, fragment);} private void hideFragment (FragmentTransaction fragmentTransaction) {Set keySet = mFragmentMap.keySet () For (String key: keySet) {Fragment fragment = mFragmentMap.get (key); fragmentTransaction.hide (fragment);}} public T showFragment (Class clazz) {return (T) createFragment (clazz);}}
Call code:
FragmentFactory mFragmentFactory = FragmentFactory.getInstance (). Init (this, R.id.fl_content); mFragmentFactory.showFragment (MyFragment1.class); mFragmentFactory.showFragment (MyFragment2.class)
The above encapsulation uses generics, factories, singletons, and so on. You only need to initialize the object once in Activity and you can manage the Fragment with one line of code, and pass in the class of the corresponding Fragment to which page you want to display.
Simple and versatile adapter
ListView is one of the most commonly used components of Android, and optimizing Litsview is essential.
The most painful thing about using Listview is to write BaseAdapter's getView () method, which is written over and over again, most of the code is redundant, but you have to write it. Let's extract the redundant code and encapsulate it.
Public abstract class CommonAdapter extends BaseAdapter {/ / the data to be displayed. The type in List is generic because you do not know the user's wrapper Bean private List mDatas; private Context mContext; / / layout file Id private int mLayoutId; public CommonAdapter (Context context,List data,int layoutId) {mDatas = data; mContext = context; mLayoutId = layoutId;} @ Override public int getCount () {return mDatas.size () } @ Override public Object getItem (int position) {return mDatas.get (position);} @ Override public long getItemId (int position) {return position;} @ Override public View getView (int position, View convertView, ViewGroup parent) {ViewHolder holder = ViewHolder.getHolder (mContext,convertView, parent, mLayoutId); setDatas (holder,getItem (position)); return holder.getConvertView () } / * set data for controls in each item * @ param holder ViewHolder * @ param object an object taken from the collection * / public abstract void setDatas (ViewHolder holder, Object object);} public class ViewHolder {private View mConvertView; / / is used to store each component in the layout in the form of key-value pair private HashMap mViews = new HashMap () / / ViewHolder constructor, which creates public ViewHolder (Context context,View convertView, ViewGroup parent, int layouId) {convertView = LayoutInflater.from (context) .propagate (layouId,parent,false); convertView.setTag (this); / / setTag () mConvertView = convertView only if convertView is empty. } / / returns a ViewHolder object public static ViewHolder getHolder (Context context, View convertView, ViewGroup parent, int layoutId) {if (convertView = = null) {return new ViewHolder (context,convertView,parent,layoutId);} else {return (ViewHolder) convertView.getTag () }} / / returns a subclass object of View, because you are not sure what components the user layout has, which is equivalent to findViewById / / returning a generic type here, or a View or Object public T getView (int resId) {View view = mViews.get (resId); / / fetching the component if (view = = null) {/ / if empty, the first screen view = mConvertView.findViewById (resId) / / find mViews.put (resId,view) from convertView;} return (T) view;} public View getConvertView () {return mConvertView;}}
Call code:
Public class MyAdapter extends CommonAdapter {public MyAdapter (Context context, List data, int layoutId) {super (context, data, layoutId);} @ Override public void setDatas (ViewHolder holder, Object object) {Bean bean = (Bean) object; ((TextView) holder.getView (R.id.title_Tv)) .setText (bean.getTitle ()); (TextView) holder.getView (R.id.desc_Tv) .setText (bean.getDesc ()) ((TextView) holder.getView (R.id.time_Tv)) .setText (bean.getTime ()); ((TextView) holder.getView (R.id.phone_Tv)) .setText (bean.getPhone ());}} List data=new ArrayList (); Bean bean=new Bean ("title 1", "content 1", "time 1", "18300000000"); Bean bean2=new Bean ("title 2", "content 2", "time 2", "18300000000") Data.add (bean); data.add (bean2); listView.setAdapter (new MyAdapter (context, data, R.layout.listview_item))
The notes are very clear, so I won't say any more.
Custom combination control, layout modularization
There must be a lot of layout redundancy in normal project development, such as the settings and navigation in the red box below.
Many people will copy these layout files over and over again, only modify the ID, strings, etc., other parts are almost exactly the same, resulting in a lot of layout file code.
The most deadly thing is not this, and write all the logic in Activity\ Fragment, making Activity\ Fragment particularly huge, really realize a piece of X code.
I think we should extract the common layout into a single xml, and then use a GroupView to deal with these logic and business, reducing the burden of activity\ Fragment.
The code is not posted, go to the source code demo to check the ParamSwitchView, this View is an Item in figure 1, encapsulating the layout and the required remote control keys to switch data around the logic.
Interface-oriented programming
Interface-oriented programming means that in an object-oriented system, the interaction between all classes or modules is done by the interface.
References to the parent class point to subclass objects and point to different subclass objects, resulting in different behaviors:
Parent a = new child A
Many children's boots often change their business during project development, such as customized system applications, and the underlying interfaces may be different on different models of TV\ mobile phones.
At this time, these underlying interfaces are encapsulated in a single class for management, and only the implementation needs to be changed when the platform changes.
Define the unified management method of interface class
Public interface IManager {void setBackLight (int value); void setPictureMode (int mode);}
Implementation Class 1
Public class HuaWeiManager implements IManager {@ Override public void setBackLight (int value) {HuaWei.savaBackLight (value);} @ Override public void setPictureMode (int mode) {HuaWei.setPictureMode (mode);}}
If the business requirement is Huawei's customized system, you only need to call Huawei's subclass.
IManager iManager=new HuaWeiManager (); iManager.setBackLight
If the business requirements are transformed into Xiaomi, then you only need to create a class to implement it.
Implementation Class 2
Public class XiaoMiManager implements IManager {@ Override public void setBackLight (int value) {XiaoMi.savaBackLight (value);} @ Override public void setPictureMode (int mode) {XiaoMi.setPictureMode (mode);}}
In the calling code, you only need to change HuaWeiManager to XiaoMiManager to adapt to other models.
/ / IManager iManager=new HuaWeiManager (); IManager iManager=new XiaoMiManager (); iManager.setBackLight
Here is only to inculcate a coding thinking, the actual development of more emergencies, not necessarily all applicable.
Be sure to take a little time to simply conceive and organize the code before coding, and don't write what comes to mind.
Pay attention to the encapsulation of tools
We often use a lot of methods that do not need to be written in the logical layer in our normal development, so we can extract them separately and manage them in separate classes.
For example: Toast, SharePreference, acquisition time, system version, network, MD5 and so on.
These things can be encapsulated and managed separately, reducing the code of the logic layer, and can also be called by other logic layers.
Bad habit
Some people like to define a tool class like Tools, in which all the tool methods are stored.
1. The network, Toast, status, time, and so on are all managed by one class, which makes it inconvenient to maintain and update later, and the code looks disorganized.
two。 Build some common methods directly at the logical level, and make a copy of the past as needed elsewhere.
Or there are other similar methods that are not encapsulated and directly copy code that used to modify only another line in other places.
Good habit
1. These tools separately create a variety of tools to store these methods, Toast only Toast-related, network-only network-related, to avoid intersecting together. It is also in line with one of the design principles: the single principle.
two。 Similar methods are extracted independently, and parameter-passing flag tags are used to distinguish application scenarios.
This is the end of this article on "sample Analysis of Android Code quality Management". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.