Write yourself a quick development Android template

Source: Internet
Author: User

I write a quick development of the Android template sometimes some code has been written before, and then the development of the time to use, you can save a lot of time, after all, written before there must be some understanding, and then write once there is no need, so this time I summed up a lot of applications need some common things, write to a template, I will use it directly in the future.   First analysis: 1. An application, first need a welcome page, used to display the company logo ah, or application logo, about two or three seconds to display.   2. Then the login registration page, almost no application is not registered?   3. Print toast, activity jumps, activity covers other activity, these basic methods.  4. Network connection, processing JSON 5. Main Page framents, most of the applications have, also add it 6. Custom Actionbar, no system comes with, custom will be more flexible summed up 6 points, and later, continue to add, first step by step ....   One, an application, the first need a welcome page, used to display the company logo ah, or application logo, about two or three seconds to display. This simple, learned Android will, directly on the code:
public class Uislashactivity extends Activity {    @Override    protected void onCreate (Bundle savedinstancestate) { C2/>super.oncreate (savedinstancestate);        Requestwindowfeature (window.feature_no_title);        GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,                WindowManager.LayoutParams.FLAG_ fullscreen);        Setcontentview (R.layout.ui_slash);    }    @Override    protected void OnStart () {        super.onstart ();        New Handler (). postdelayed (New Thread () {            @Override public            void Run () {                startactivity (new Intent ( Uislashactivity.this,uistartactivity.class));                Finish ();}}        , +);}    }

I show here is three seconds, according to the actual needs to change, here is to pay attention to the full screen, as for the layout code is not affixed, my layout is just a imageview. Second, then is the landing registration page, almost no application is not registered it? Between Slashactivity and Login,register there is a choice to register or login startactivity, this startactivity only two buttons, login, or register, the code is very simple, do not post, easy to understand, right
I have seen a lot of applications This page is the login registration button different colors, where the registration button is more white, but still according to their own needs, change the color. Then is the login registration page, both pages are startactivity sub-page, can be configured in the main configuration file, the code is as follows:
<activity            android:name= "com.example.ui.UiLoginActivity"            android:label= "@string/login"            android: Parentactivityname= "Com.example.ui.UiStartActivity" >        </activity>        <activity            android: Name= "com.example.ui.UiRegisterActivity"            android:parentactivityname= "com.example.ui.UiStartActivity            " Android:label= "@string/register"            >        </activity>

The effect of this is that the Login registration page has a return button above the Actionbar. Login Registration page code each application is slightly different, here does not say, I wrote only one Editext and two buttons. Landing in, is the main page. The main page is described below. Three. Main Page framents, most of the applications have, also add it I did not start here as summarized above to write, because the feeling from the landing in writing this angle will be more smooth. From the general to the details. The main page is more complex, an activity, several frament. First say the bottom of the navigation bar, you can use the button, you can also rewrite the view, here choose to rewrite the view, at the same time in order to achieve horizontal drag, you can also convert frament also have a viewpaper, I here with three frament for example.
public class Uimyframentactivity extends Fragmentactivity implements EventListener, Onpagechangelistener,onclicklistener{private Viewpager Mviewpager; 
Below three framentprivate contactfragment contactfragment;private myinformationfragment myinformationfragment;private    Recentfragment recentfragment; Private fragment[] fragments;private fragmentpageradapter madapter;private int index;private int currentTabIndex;// Which Framentprivate is currently list<bottomtabview> views = new arraylist<bottomtabview> ();//view that holds the bottom navigation bar Bottomtabview one = null; Bottomtabview-n = null; Bottomtabview three = null, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.frament_footer); Initview ();}  private void Initview () {Mviewpager = (Viewpager) Findviewbyid (R.id.id_viewpager); InitTab (); Madapter = new Fragmentpageradapter (Getsupportfragmentmanager ()) {@Overridepublic int getcount () {return Fragments.length;} @Overridepublic Fragment getItem (int arg0) {return fragments[arg0];}}; Mviewpager.setadapter (Madapter);//mviewpager.setpagetransformer (True, New Mytransformer ()); Mviewpager.setonpagechangelistEner (this), one = (Bottomtabview) Findviewbyid (R.id.id_indicator_one), and one = (Bottomtabview) Findviewbyid (R.id.id_     Indicator_two); three = (Bottomtabview) Findviewbyid (R.id.id_indicator_three); Views.add (one), Views.add (one), Views.add (three); One.setonclicklistener (This), Two.setonclicklistener (This), Three.setonclicklistener (this); One.seticonalpha (1.0f);} private void InitTab () {recentfragment = new recentfragment (); contactfragment = new Contactfragment (); Myinformationfragment = new Myinformationfragment (); fragments = new fragment[] {recentfragment, contactfragment, Myinformationfragment};//Getsupportfragmentmanager (). BeginTransaction (). Add (R.id.fragment_container, recentfragment).//Add (R.id.fragment_container, contactfragment). Add (R.id.fragment_container, myinformationfragment). Hide (Contactfragment). Show (Recentfragment). commit ();}  @Overrideprotected void Onresume () {//TODO auto-generated method Stubsuper.onresume (); } @Overrideprotected void OnPause () {//TODO auto-generated methodStubsuper.onpause (); } private static Long firsttime; @Overridepublic void onbackpressed () {//TODO auto-generated method stubif (Firsttime + > System.currenttimemillis ()) {super.onbackpressed ();} else {toast.maketext (uimyframentactivity.this, "One more click to quit", Toast.length_long). Show (); Firsttime = System.currenttimemillis ();}  @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); }/** * This method is called when the state changes, where the arg0 parameter has three states (0,1,2). * Arg0 ==1 The time implied is sliding, arg0==2 the hour of the tacit slide is finished, arg0==0 the hour implied that nothing did. */@Overridepublic void onpagescrollstatechanged (int arg0) {if (arg0>0) {contactfragment temp = (contactfragment) Fragments[1];//temp.resetsidebar ();} } @Overridepublic void onpagescrolled (int position, float Positionoffset,int positionoffsetpixels) {if (Positionoffset & Gt 0) {Bottomtabview left = Views.get (position); Bottomtabview right = Views.get (position + 1); Left.seticonalpha (1-positionoffset); Right.seticonalpha (Positionoffset  ); }} @Overridepublic VoID onpageselected (int arg0) {log.i ("frament", "create" +arg0); Fragments[arg0].onresume (); if (arg0==1) {    One.setdrawflag (FALSE);}} @Overridepublic void OnClick (View v) {resetothertabs (); switch (V.getid ()) {case R.id.id_indicator_one:views.get (0). Seticonalpha (1.0f);//views.get (0). Setdrawflag (!views.get (0). Getdrawflag ()); Mviewpager.setcurrentitem (0, false); Break;case r.id.id_indicator_two:views.get (1). Seticonalpha (1.0f); Mviewpager.setcurrentitem (1, false); break;case R.id.id_indicator_three:views.get (2). Seticonalpha (1.0f); Mviewpager.setcurrentitem (2, false); break; }}/** * Resets the other tab */private void Resetothertabs () {for (int i = 0; i < views.size (); i++) {Views.get (i). Seticonalpha (0);} }}

This allows you to click on the bottom navigation bar, or cross-drag to achieve framents switch,
@Overridepublic void onbackpressed () {//TODO auto-generated method stubif (Firsttime + > System.currenttimemillis ()) {super.onbackpressed ();} else {toast.maketext (uimyframentactivity.this, "One more click to quit", Toast.length_long). Show (); Firsttime = System.currenttimemillis ();}
The above function is worth noting that many applications have a scheme to prevent the application exit due to user error action, that is, a certain time to click the return key two times before exiting the application, the above function is to achieve this function, two seconds, click the return key two times will quit the app! As for frament here does not say, each application is too big, here only write about the same place. Four, the custom Actionbaractionbar is also changeable, more common is the middle of a title, about two each one icon, or the right there is a button to hide multiple options, here say the first
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "style=" @style/actionbar "android:baselinealigned=" false "android:focusable=" true "> <linearlayo UT android:id= "@+id/header_layout_leftview_container" android:layout_width= "Wrap_content" Android:lay        out_height= "Fill_parent" android:layout_alignparentleft= "true" android:gravity= "Center_vertical|left" android:orientation= "Horizontal" > </LinearLayout> <linearlayout android:id= "@+id/header_layout_ Middleview_container "android:layout_width=" wrap_content "android:layout_height=" Fill_parent "Android : Layout_centerhorizontal= "True" android:layout_centervertical= "true" android:gravity= "center" Android                        : orientation= "Horizontal" > <textview android:id= "@+id/header_htv_subtitle" Android:layout_width= "Wrap_conteNT "android:layout_height=" Wrap_content "/> </LinearLayout> <linearlayout android:id=" @+id/header_layout_rightview_container "android:layout_width=" wrap_content "android:layout_height=" Fill_pare NT "android:layout_alignparentright=" true "android:gravity=" Center_vertical|right "Android:orientatio n= "Horizontal" > </LinearLayout></RelativeLayout>

This is the middle title. Use can be, mainly change too much. Can be changed according to requirements. Five, assorted tool class encryption, compression, processing strings and so on.
public class Apputil {/* MD5 encryption */static public string MD5 (String str) {MessageDigest algorithm = null;try {algorithm = M Essagedigest.getinstance ("MD5");} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} if (algorithm! = null) {Algorithm.reset (); Algorithm.update (Str.getbytes ()); byte[] bytes = Algorithm.digest (); StringBuilder hexstring = new StringBuilder (); for (byte b:bytes) {hexstring.append (integer.tohexstring (0xFF & B));} return hexstring.tostring ();} Return "";} /* Initial capital */static public String Ucfirst (string str) {if (str! = NULL && str! = "") {str = str.substring (0,1). ToU Ppercase () +str.substring (1);} return str;} /* Add gzip decompression function to entityutils.tostring () */public static string gziptostring (final httpentity entity, final String default Charset) throws IOException, ParseException {if (entity = = null) {throw new IllegalArgumentException ("HTTP entity may not be null ");} InputStream instream = Entity.getcontent (); if (instream = = null) {return "";} Gzip Logic Startif(Entity.getcontentencoding (). GetValue (). Contains ("gzip")) {instream = new Gzipinputstream (instream);} Gzip Logic endif (Entity.getcontentlength () > Integer.max_value) {throw new IllegalArgumentException ("HTTP entity t OO large to being buffered in memory ");} int i = (int) entity.getcontentlength (); if (I < 0) {i = 4096;} String charset = Entityutils.getcontentcharset (entity), if (charset = = null) {charset = Defaultcharset;} if (charset = = null) {charset = HTTP. Default_content_charset;} Reader reader = new InputStreamReader (instream, CharSet);  Chararraybuffer buffer = new Chararraybuffer (i); try {char[] tmp = new Char[1024];int l;while ((l = reader.read (tmp))! =-1) {buffer.append (tmp, 0, L);}} finally {reader.close ();} return buffer.tostring ();} /* Add gzip decompression function to entityutils.tostring () */public static String gziptostring (final httpentity entity) throws IOException, P arseexception {return gziptostring (entity, NULL);} public static sharedpreferences getsharedpreferences (Context ctx) {return CTX.GEtsharedpreferences ("Com.app.demos.sp.global", Context.mode_private);} public static sharedpreferences getsharedpreferences (service service) {return service.getsharedpreferences (" Com.app.demos.sp.global ", context.mode_private);} Business logic/* Determine if int is empty */static public boolean isemptyint (int v) {Integer t = new Integer (v); return t = = null? True:false;} /* Gets the number of milliseconds */public static long Gettimemillis () {return System.currenttimemillis ();} /* Get consumed memory */public static long Getusedmemory () {Long total = Runtime.getruntime (). TotalMemory (); Long free = Runtime.getru Ntime (). Freememory (); return total-free;}}
Six, network connection, JSON processing network connection, I use the android-async-http framework, the use of other people's framework will be more secure, because other people do the time to consider the network links a lot of security issues, and this piece of knowledge I do not know deeply, so still use others ' good, The process of JSON is a tool class, and it is changed according to the requirements, because some people like to wrap the received JSON information into a class, and sometimes do not need. Seven, summed up to write a blog summary can be said to be warm so know new Ah, previously written things, now forget almost, re-see the code above there are a lot of shortcomings, but also need to optimize these code, continue efforts!

Code Download: http://download.csdn.net/detail/u013013970/8930227

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Write yourself a quick development Android template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.