Teach you how to make a good APP from scratch

Source: Internet
Author: User
Tags gettext

Objective

Start from scratch and take you to a "focus on app" before bedtime. " Before going to bed if you can have an APP, can let us write a story of this day or experience, at the same time can see the jokes, a good look at the sister, relax a tired body and mind that much good, this is the reason I finished this APP. All the code I've shared with the APP? Github, need to click here directly, if you like, trouble to give a star, thank you.

This article is a summary of this series of articles, if you feel that the space is too long, please click on the link below

Teach you to do a good-looking app-day one from scratch

Teach you to do a good-looking app-day from scratch

Teach you to do a good-looking app-day from scratch three

Teach you to do a good-looking app-day four from scratch.

Teach you to do a good-looking app-day from scratch Five

Before starting the text, let's start with a wave of effects, and see what we can achieve in five days.

This tutorial is divided into 5 days, the content is:

    • Day one, preparing

      • Functional Requirements
      • Feasibility analysis
    • Day Two,ui and public class packages

      • Design and implementation of interface
      • Implementation of public classes
    • Day three, Diary module

      • Diary of the Show
      • Implementation of the hover menu
      • The realization of adding and deleting diary
    • Day four, sister module

      • Getting the picture
      • Display of pictures
      • Display of the Details page
    • Day five, Satin module
      • Getting the Satin data
      • The display of the satin
Day One

As the saying goes, the beginning of everything is difficult, before the start of the code, let us do some necessary preparation, so as to be more effective!

First, functional requirements

Since to do an app, then we have to put the function of the app are listed, with the direction to better efforts, because I want to do is a dedicated to sleep before the app, so I think there should be the following these features

    • 1, the diary changes and additions
    • 2. Show some fun and fun jokes
    • 3, waterfall flow show beautiful sister
    • 4, save the contents of the diary and cache sister pictures

Although the demand is not much, but to apply to the network, data storage, image caching, UI design and other content, I believe the entire APP to complete, it will certainly be able to consolidate our Android foundation.

Second, feasibility analysis

Our APP mainly has three modules, diary module is mainly applied to the knowledge of the database, not very difficult. However, the Satin module and the sister module of the data from where to come, this is to think about it. Fortunately now is an open-source era, a lot of data, the Internet has been open source.

Let's look at the contents of the data first

group:?{        text:?"教授在河边,常常看到两只龟,缩着一动不动。有天忍不住好奇,问一农              民:这两只乌龟在干吗?农民说:他们在pk。教授不解地问:动都没动过p什么            k。老农说:他们在比谁寿命长。教授说:可是壳上有甲骨文的那只,早就死了埃        这时,另一只猛然探出头来骂到:md,死了也不吭一声!有甲骨文的那只也伸        出头来:“专家说啥你信啥1",        user:?{              user_id:?4669064575,              name:?"馒头啊",              avatar_url:?"http://p3.pstatp.com/medium/6237/7969345239",},          content:?"教授在河边,常常看到两只龟,缩着一动不动。有天忍不住好奇,问                   一农民:这两只乌龟在干吗?农民说:他们在pk。教授不解地问:动都没动过           p什么k。老农说:他们在比谁寿命长。教授说:可是壳上有甲骨文的那只,早           就死了埃这时,另一只猛然探出头来骂到:md,死了也不吭一声!有甲骨文           的那只也伸出头来:“专家说啥你信啥1",...  }
{          id:?"56cc6d1d421aa95caa7076df",          type:?"福利",          url:?"http://ww1.sinaimg.cn/large/7a8aed7bgw1esxxi1vbq0j20qo0hstcu.jpg",          used:?true,          who:?"张涵宇"}

The above two pieces of code are the JSON type data of the joke and the sister module, I have removed some useless fields. The rest is the data we want. You can see the content in the satin data, with the jokes, and the publisher's avatar and name. The sister data has a picture of the URL, id, and the type of picture. I believe that with such a wealth of data, we want to complete the APP is also a strong.

Day of First, the design and implementation of the interface

Since we want to finish a good-looking app, then good-looking interface is essential, here I strongly recommend that the APP interface design must comply with Google's proposed Material, in this recommendation a can let us achieve Material design Become more simple site material Design palette, I this APP color is to use this website to complete, paste a few pictures, let you feel it's powerful

With the help of this site can let us complete the application of color and icon collection, for the next step of the realization of the function, first lay the foundation, as for the interface design is benevolent see, Space is limited, I will not speak more.

The APP's final design results are as follows:

Second, the realization of public class

Because this project has three modules, there are some things can be common, if we first put these things to be generic, encapsulated, to provide all the module calls, we believe that will greatly improve our development efficiency.

1, the Network tool class package

In this app, a lot of places have to use the network request, so it is necessary to encapsulate the network request, because the size of the app is small, so I chose volley this network framework as our network request library, the network request package, which place needs, call on the line. For the network request, I think every programmer should know a bit of HTTP, here is attached an article about HTTP, the programmer should understand the point of HTTP.

Let's start by writing an interface that makes callbacks to network requests.

public interface VolleyResponseCallback {    void onSuccess(String response);    void onError(VolleyError error);}

Then encapsulate the network request.

public class VolleyHelper {    /**     * 用于发送 Get 请求的封装方法     *     * @param context Activity 的实例     * @param url 请求的地址     * @param callback 用于网络回调的接口     */    public static void sendHttpGet(Context context, String url, final VolleyResponseCallback callback){        RequestQueue requestQueue = Volley.newRequestQueue(context);        StringRequest stringRequest = new StringRequest(url                , new Response.Listener<String>() {            @Override            public void onResponse(String s) {                callback.onSuccess(s);            }        }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError error) {                callback.onError(error);            }        });        requestQueue.add(stringRequest);    }}
2. Json-Parsed helper classes

Because the data we get in this APP is in JSON format, it is necessary to encapsulate the JSON parsing into a tool class, pass in a String type of data, and get the List of the data entity class directly.

public class Commonparser {/** * is used to parse a list of JSON data * such as: * {"Success": true, "fileList": [{"filename": "FileName 1", "fil     Esize ":" File Size 1 "}, * {" filename ":" Filenames 2 "," FileSize ":" File Size 2 "}]} * * @param the JSON data returned by the result network such as: the entire string of data above * @param successkey A field that determines whether the network is successful, such as the success field above * @param The fields of the Arrkey list such as the FileList field above * @param Clazz the type of bean to parse into * @param <T> type of bean to parse into * @return */public static <T> List&lt ; T> parseforlist (string result, string Successkey, String arrkey, class<t> clazz) {list<t> List = NE        W arraylist<> ();        Jsonobject rootjsonobject = null;            try {rootjsonobject = new Jsonobject (result);                 if (Rootjsonobject.getboolean (Successkey)) {Jsonarray Rootjsonarray = Rootjsonobject.getjsonarray (ArrKey);                Gson g = new Gson (); for (int i = 0; i < rootjsonarray.length (); i++) {Tt = G.fromjson (Rootjsonarray.getjsonobject (i). toString (), clazz);                List.add (t);        }}} catch (Jsonexception e) {e.printstacktrace ();    } return list; }}
3, Homeactivity (Main page) of the package

The main page I use is Tablayout + Viewpager + Fragment, is also now the mainstream APP Main page display way. The bottom of the main interface is the icon and name of our three modules, which allows the interface to jump through the left and right slide.

The entity class for the bottom icon Commontabbean
public class CommonTabBean implements CustomTabEntity{    private int selectedIcon;    private int unselectedIcon;    private String title;    public CommonTabBean(String title){        this.title = title;    }    public CommonTabBean(String title, int selectedIcon, int unselectedIcon) {        this.title = title;        this.selectedIcon = selectedIcon;        this.unselectedIcon = unselectedIcon;    }    @Override    public String getTabTitle() {        return title;    }    @Override    public int getTabSelectedIcon() {        return selectedIcon;    }    @Override    public int getTabUnselectedIcon() {        return unselectedIcon;    }}
Viewpager + Fragment General-purpose Adapter
public class CommonPagerAdapter extends FragmentPagerAdapter {    private List<Fragment> mFragments;    public CommonPagerAdapter(FragmentManager fragmentManager, List<Fragment> mFragments){        super(fragmentManager);        this.mFragments = mFragments;    }    @Override    public Fragment getItem(int position) {        return mFragments.get(position);    }    @Override    public int getCount() {        return mFragments.size();    }}
Day three

About the implementation of the diary module, in fact, I used to write a diary of the APP, specific ideas and practices, you can refer to my article Android a very simple, elegant diary app

Day four First, the image of the acquisition 1, based on the returned data to write a picture of the entity class
public class MeiziBean {    @SerializedName("_id")    private String id;    @SerializedName("url")    private String imageUrl;    @SerializedName("who")    private String who;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getImageUrl() {        return imageUrl;    }    public MeiziBean(String imageUrl){        this.imageUrl = imageUrl;    }}
2, the picture display

You can see that I am using waterfall flow to achieve the display of the picture, the effect is good, but in fact, it is very simple to achieve.

First write the layout of the picture as Recyclerview Item

<android.support.v7.widget.CardView    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content">                <ImageView                    android:id="@+id/item_iv_meizi"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_centerHorizontal="true"                    android:layout_centerVertical="true"                    /></android.support.v7.widget.CardView>

Can see I add a cardview outside the ImageView, this kind of card-type layout, can make the picture look like a card, quite elegant, beautiful.

Then write the Adapter, bind the data and the interface

public class Meiziadapter extends recyclerview.adapter<meiziadapter.meiziviewholder> {private list<    Meizibean> mmeizibeanlist;    Private Fragment mfragment; Public Meiziadapter (list<meizibean> mmeizibeanlist, Fragment mfragment) {this.mmeizibeanlist = MMeiziBeanList        ;    This.mfragment = mfragment; } @Override Public Meiziviewholder oncreateviewholder (viewgroup parent, int viewtype) {View view = Layoutinf        Later.from (Parent.getcontext ()). Inflate (R.layout.item_meizi, NULL);    return new Meiziviewholder (view);                } @Override public void Onbindviewholder (Meiziviewholder holder, final int position) {Glide.with (mfragment)                 . Load (mmeizibeanlist.get (position). Getimageurl ()). Fitcenter (). Dontanimate ()        . Diskcachestrategy (Diskcachestrategy.all). into (Holder.mivmeizi); Holder.mIvMeizi.setOnClickListener (New View.onclicklistener () {@OverRide public void OnClick (View v) {arraylist<string> resultlist = new arraylist<string&                gt; ();                for (Meizibean meizibean:mmeizibeanlist) {Resultlist.add (Meizibean.getimageurl ());            } detailactivity.startactivity (Mfragment.getactivity (), resultlist, position);    }        }); } @Override public int getitemcount () {if (mmeizibeanlist.size () > 0) {return mmeizibeanlist.si        Ze ();    } return 0;        } public static class Meiziviewholder extends recyclerview.viewholder{ImageView Mivmeizi;            Public Meiziviewholder (View Itemview) {super (Itemview);        Mivmeizi = (ImageView) Itemview.findviewbyid (R.id.item_iv_meizi); }    }}

The

Finally gets the data in Fragment, and the layout is initialized.

public class Meizifragment extends Fragment {... @Nullable @Override public View Oncreateview (Layoutinflat Er inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) {View view = Inflater.inflate (R.L        Ayout.fragment_meizi, container, false);        Butterknife.bind (this, view);        Initview ();        Refreshmeizi ();    return view; }/** * Refreshes the current interface */private void Refreshmeizi () {mrefresh.setcolorschemeresources (r.color.colorprimary        ); Mrefresh.setonrefreshlistener (New Swiperefreshlayout.onrefreshlistener () {@Override public void OnR                Efresh () {Initview ();            Mrefresh.setrefreshing (FALSE);    }        }); } private void Initview () {Volleyhelper.sendhttpget (Getactivity (), Meiziapi.getmeiziapi (), New Volleyresponseca                Llback () {@Override public void onsuccess (String s) {response = s; MeiziBeanlist = Gsonhelper.getmeizibean (response);                Mrvshowmeizi.setlayoutmanager (New Staggeredgridlayoutmanager (2, staggeredgridlayoutmanager.vertical));                Collections.shuffle (meizibeanlist);            Mrvshowmeizi.setadapter (New Meiziadapter (Meizibeanlist, meizifragment.this));            } @Override public void OnError (Volleyerror error) {LOGGER.D (error);    }        }); }
3, the details of the page display

Dry, the whole module can only show sister's pictures how to do it!!! You have to be able to see the big picture, zoom in and out according to the gesture, and browse to the next picture just go, say dry.

Because the picture needs to have the function of zooming in and out according to the gesture, so I think of PhotoView, which is written by a great God on the net, inherits from ImageView a custom control. Picture loading I used to be
Glide, if you do not know the library, highly recommended, a line of code can handle the image loading, you are sure not to study. Attached here is an article about Glide Glide a powerful picture loading frame

public class Detailfragment extends Fragment {public static detailfragment newinstance (String imageUrl) {Detai        Lfragment fragment = new Detailfragment ();        Bundle bundle = new bundle ();        Bundle.putstring (Image_url, IMAGEURL);        Fragment.setarguments (bundle);    return fragment; } @Nullable @Override public View oncreateview (Layoutinflater inflater, @Nullable viewgroup container, @Nullable        Bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment_detail, container, false);        Butterknife.bind (this, view);        Bundle bundle = Getarguments ();        String imageUrl = bundle.getstring (Image_url);        Glide.with (this). Load (IMAGEURL). into (Mpvshowphoto); Mpvshowphoto.setonphototaplistener (New Photoviewattacher.onphototaplistener () {@Override public voi            D Onphototap (view view, float V, float v1) {getactivity (). Finish (); } @Override Public VOID Onoutsidephototap () {}});    return view; }}
Day five First, the acquisition of the satin data

The access to the satin data is essentially the same as that of the sister module.

Write the entity class first

public class DuanziBean {    @SerializedName("group")    private GroupBean groupBean;    private String type;    public GroupBean getGroupBean() {        return groupBean;    }    public void setGroupBean(GroupBean groupBean) {        this.groupBean = groupBean;    }    public String getType() {        return type;    }    public void setType(String type) {        this.type = type;    }}
public class GroupBean {    private String text;    private long id;    private UserBean user;    public String getText() {        return text;    }    public long getId() {        return id;    }    public UserBean getUser() {        return user;    }    public static class UserBean {        private long user_id;        private String name;        private String avatar_url;        public String getName() {            return name;        }        public String getAvatar_url() {            return avatar_url;        }    }}

After writing the entity class, we can parse the returned data into a List containing the Satin entity class using the Network request tool and the parsing tool that we have previously encapsulated.

Second, the display of the satin

The usual, write a recyclerview Item first.

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_paren T "android:layout_height=" match_parent "android:orientation=" vertical "> <linearlayo        UT android:layout_width= "match_parent" android:layout_height= "40DP" android:paddingleft= "8DP" > <de.hdodenhof.circleimageview.circleimageview android:id= "@+id/duanzi_civ_avatar" and Roid:layout_width= "24DP" android:layout_height= "24DP" android:src= "@drawable/avatar" Android            oid:layout_gravity= "center"/> <textview android:id= "@+id/duanzi_tv_author"            android:paddingleft= "8DP" android:paddingstart= "8DP" android:layout_width= "Match_parent"            android:layout_height= "16DP" android:text= "Developerhaoz" android:layout_gravity= "center_vertical" /> </linearlayout> <textview android:id= "@+id/duanzi_tv_content" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:paddingbottom= "10DP" android:paddingleft= "40DP" Android oid:paddingright= "10DP" android:text= ""/> <include layout= "@layout/layout_app_divide"/></lin Earlayout>

Then write the Adapter that binds the data and interface

public class Duanziadapter extends recyclerview.adapter<duanziadapter.duanziviewholder>{private Fragment    Mfragment;    Private list<duanzibean> mduanzibeanlist;        Public Duanziadapter (Fragment Fragment, list<duanzibean> duanzibeanlist) {this.mfragment = Fragment;    This.mduanzibeanlist = duanzibeanlist; } @Override Public Duanziviewholder oncreateviewholder (viewgroup parent, int viewtype) {View view = Layoutin        Flater.from (Parent.getcontext ()). Inflate (R.layout.item_duanzi, NULL);    return new Duanziviewholder (view);  } @Override public void Onbindviewholder (duanziviewholder holder, int position) {try {Duanzibean            Duanzibean = Mduanzibeanlist.get (position);            Glide.with (mfragment). Load (Duanzibean.getgroupbean (). GetUser (). Getavatar_url ()). into (Holder.mcivavatar);            Holder.mTvContent.setText (Duanzibean.getgroupbean (). GetText ()); Holder.mTvAuthor.setText (Duanzibean.getgroupbean ().GetUser (). GetName ());        } catch (Exception e) {e.printstacktrace ();    }} @Override public int getitemcount () {return mduanzibeanlist.size ();        } public static class Duanziviewholder extends recyclerview.viewholder{private Circleimageview Mcivavatar;        Private TextView Mtvauthor;        Private TextView mtvcontent;            Public Duanziviewholder (View Itemview) {super (Itemview);            Mcivavatar = (Circleimageview) Itemview.findviewbyid (R.id.duanzi_civ_avatar);            Mtvauthor = (TextView) Itemview.findviewbyid (R.id.duanzi_tv_author);        Mtvcontent = (TextView) Itemview.findviewbyid (r.id.duanzi_tv_content); }    }}

Data and fetch in the final satin page and initialization of the interface

public class Duanzifragment extends Fragment {@Nullable @Override public View oncreateview (Layoutinflater Inflat Er, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fra        Gment_duanzi, container, false);        Butterknife.bind (this, view);        Initview ();        Initrefresh ();    return view;        } private void Initrefresh () {mrefresh.setcolorschemeresources (r.color.colorprimary); Mrefresh.setonrefreshlistener (New Swiperefreshlayout.onrefreshlistener () {@Override public void OnR                Efresh () {Initview ();            Mrefresh.setrefreshing (FALSE);    }        }); } private void Initview () {Volleyhelper.sendhttpget (Getactivity (), Duanziapi.get_duanzi, new Volleyresponsecall Back () {@Override public void onsuccess (String response) {list<duanzibean> MD Uanzibeanlist = gsonhelper.getduanzibeanlIST (response);                Mduanzibeanlist.remove (3);                Mrvshowduanzi.setlayoutmanager (New Linearlayoutmanager (Getactivity ()));            Mrvshowduanzi.setadapter (New Duanziadapter (Duanzifragment.this, mduanzibeanlist));            } @Override public void OnError (Volleyerror error) {LOGGER.D (error);    }        }); }}

This is the entire content of this article, this APP all the code I have already shared on Github, if it is helpful to you, I would like a star bar.

Guess you like it.
    • Android a very simple, elegant diary APP
    • Android can make you less detours of dry cleaning
    • Android Roll up sleeves, package yourself dialogfragment

Teach you how to make a good APP from scratch

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.