Introduction to low threshold--Turing robot development

Source: Internet
Author: User

In my spare time, I think of a Turing robot development video that I saw before. Directly on their official website to see the developer's manual, I wrote a Turing device man small application. The idea of writing basic and online some development video coincide, are network access +json analysis, and the other is to design a good-looking interface. Interested students can be based on their own needs to make changes or even refine the query function inside, can make a complete application of the app. First look at my demo effect:




This project mainly consists of three parts: UI design and development, call Turing API to get data JSON parsing encapsulated into bean, ListView optimization display.


UI design and development

First look at the UI layout of the entire XML



The layout is simple, and you can see the layout from the top left corner. This is easy for Android developers, where the ListView uses the following settings to fill the middle space.


        Android:layout_width= "Match_parent"        android:layout_height= "0DP"        android:layout_weight= "1"


The main focus of the overall UI design is on the implementation of the chat border and the use of shape and selector.

Edge shape file with rounded corners (take edittext for example)


<?xml version= "1.0" encoding= "UTF-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android"    android:shape= "Rectangle" >    <gradient        android:endcolor= "#ffffff"        android:startcolor= "# Ffffff "/>    <corners        android:bottomleftradius=" 5DP "        android:bottomrightradius=" 5DP        " android:topleftradius= "5DP"        android:toprightradius= "5DP"/>    <stroke        android:width= "1dip"        android:color= "#ffffff"/></shape>


Use rounded corners and implement selector files (take button for example)


<?xml version= "1.0" encoding= "Utf-8"? ><selector xmlns:android= "http://schemas.android.com/apk/res/ Android ">    <item android:state_focused=" true "        android:state_pressed=" true "        android:drawable=" @ Drawable/start_clickafter "/>    <item android:state_focused=" false "        android:state_pressed=" true "        android:drawable= "@drawable/start_clickafter"/>    <item        android:state_selected= "true"        android:drawable= "@drawable/start_clickafter"        />    <item        android:state_focused= "true"        android:drawable= "@drawable/start_clickafter"        />    <!--default background picture--    <item android:state _focused= "false" android:drawable= "@drawable/start_clickbefore"/></selector>

For the chat box configuration, we need to implement the left and right chat box effect (as shown)




We need to configure the left and right two XML layouts.

The left layout is as follows:


<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" match_parent "android:layout_height=" Match_parent "&    Gt <textview android:id= "@+id/id_time" android:layout_width= "fill_parent" android:layout_height= "wrap    _content "android:textsize=" 10SP "android:layout_alignparenttop=" true "android:gravity=" center "/> <com.example.yummylau.turingrobot.ui.circularimage android:layout_below= "@+id/id_time" android:id= "@+i     D/id_iv "android:layout_width=" 50DP "android:layout_height=" 50DP "android:padding=" 10DP "/> <textview android:layout_below= "@+id/id_time" android:layout_margintop= "10DP" android:layout_m arginleft= "5DP" android:layout_marginright= "50DP" android:layout_torightof= "@+id/id_iv" android:layou    T_width= "Wrap_content"    android:layout_height= "Wrap_content" android:id= "@+id/id_tv" android:gravity= "Center_vertical" an Droid:textsize= "17SP" android:background= "@drawable/aio_friend_bg_nor_11"/></relativelayout>


The right layout is as follows:


<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" match_parent "android:layout_height=" Match_parent "&    Gt <textview android:id= "@+id/id_time" android:layout_width= "fill_parent" android:layout_height= "wrap    _content "android:textsize=" 10SP "android:layout_alignparenttop=" true "android:gravity=" center "/> <com.example.yummylau.turingrobot.ui.circularimage android:layout_below= "@+id/id_time" Android:layout_ Alignparentright= "true" android:id= "@+id/id_iv" android:layout_width= "50DP" android:layout_height= "50 DP "android:padding=" 10DP "/> <textview android:layout_below=" @+id/id_time "android:l ayout_margintop= "10DP" android:layout_marginright= "5DP" android:layout_marginleft= "50DP" Android:layo  ut_toleftof= "@+id/id_iv"      Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:id= "@+id/id_tv" Android:gravity= "center_vertical" android:textsize= "17SP" android:background= "@drawable/aio_user_bg_nor_11 "/></relativelayout>


One of the com.example.yummylau.turingrobot.ui.CircularImage is my own realization of a round head. Interested students can download the source code at the bottom of the reference. In fact, these layouts are not difficult, the most important thing is to deal with the "chat bubble" production. I am using Android studio to bring my own tools (highly recommended)




I used the. 9.png tool to implement the chat bubble. If not the Android Studio IDE, you can start this tool by double-clicking Draw9.path.bat in your own Android Sdk\tools directory.

(1) The length of the 1DP is drawn on the upper and the left, and the length is used for stretching. If the content in your picture is too wide or too high, it will be extended in the same way as the height of your stroke. For example, if your content is more than 300DP in the vertical direction, then the image will automatically increase the length of the 300X1DP to fit your content at the point on the left of the conversation (we are 1DP).

(2) The right and the bottom of the general picture is relatively long. In the above picture, we see two rectangles overlap, and the overlapping part is what our users use to store the content. Click "Show content" to see a demo of the contents fill on the right.

learned. 9.png processing, no longer worry about the picture deformation. The UI design and development of the entire application is roughly the same.


call Turing API to get data JSON parsing encapsulated into BeanOpen the Turing http://www.tuling123.com/openapi/website, first register their own account, and then into the personal center. Find your own API KEY and save it locally. There are many functions in the personal Center: robot setting, robot tuning and so on. You can let your own Turing the person study independently, answer the specified question and so on. Interested friends can continue to study. calling the official API is simple, just use the Get method to integrate the key and the message that needs to be sent (string) to the URL and then access it, and get the String returned by the system for JSON parsing. There are only a few steps to follow
(1) Rewrite your network access class (according to your hobby), the code is as follows:
Package Com.example.yummy.turingrobot;import Android.os.asynctask;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Java.io.bufferedreader;import java.io.inputstream;import java.io.inputstreamreader;/** * Asynchronous Network Access class * Created by Yummy on 2015/7/12.    */public class Myasync extends asynctask<string,void,string>{private String URL;    Private HttpClient HttpClient;    Private HttpGet HttpGet;    Private HttpResponse HttpResponse;    Private Httpentity httpentity;    Private InputStream InputStream;    The method of using callback private calldata data;        Public myasync (String URL, calldata data) {this.url = URL;    This.data = data; /** * For background network access get data * @param params * @return */@Override protected String doinbackground (Strin G ... params) {try{httpClient = new DEFAULTHTTPCLient ();            HttpGet = new HttpGet (URL);            HttpResponse = Httpclient.execute (HttpGet);            Httpentity = Httpresponse.getentity ();            Httpresponse.getstatusline ();            InputStream = Httpentity.getcontent ();            BufferedReader BufferedReader = new BufferedReader (new InputStreamReader (InputStream));            String line = null;            StringBuffer StringBuffer = new StringBuffer ();            while (line = Bufferedreader.readline ())!=null) {stringbuffer.append (line);        } return stringbuffer.tostring ();        }catch (Exception e) {return new String ("Pro, access Error Oh!");    }} @Override protected void OnPostExecute (String s) {Data.getdataurl (s); }}

(2) Write a data interface that allows Asynctask to callback the Mainactivity component for display. (It is also common toAsynctask in the constructor of the mainactivity to invoke its components)
Package com.example.yummy.turingrobot;/** * Data Callback interface * Created by yummy on 2015/7/12. */public interface Calldata {    void Getdataurl (String data);}

(3) Mainactivity Implement interface and make network request (part of code)
    @Override public         void Getdataurl (String data) {        System.out.println (data);        Lists.add (Dataparse (data));        Notice change        adapter.notifydatasetchanged ();    }

            Myasync Myasync = (myasync) New Myasync ("Http://www.tuling123.com/openapi/api?" +                    "key=< own key>" + "Send Content", This). Execute ();

(4) Data parsing encapsulated as Bean
    /**     * Parse Data     * @param result     * @return     *    /Public Bean dataparse (String result) {        try{            if ( Result.equals ("Pro, you're not connected yet!")) {                Bean listData = new Bean (result, bean.receiver,gettime ());                return listData;            } else{                jsonobject jsonobject = new Jsonobject (result);                Bean listData = new Bean (jsonobject.getstring ("text"), Bean.receiver,gettime ());                return listData;            }        } catch (Exception e) {            return null;        }    }

optimized display of the ListViewbecause of the left and right side layouts, the traditional ListView optimization method needs to be improved. In general we use Viewholder for caching, but because of the multiple layouts, we should be able to correspond to multiple layout caches. Policy: Use multiple viewholder for caching, and give different flags based on different layouts, and then make judgments in the GetView method. The specific code is as follows:
Package Com.example.yummy.turingrobot;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.TextView; Import Com.example.yummylau.turingrobot.ui.circularimage;import java.util.list;/** * Adapter * Created by yummy on 2015/7/    */public class Adapter extends baseadapter{private list<bean> lists;    Private context context;    Private Layoutinflater Inflater;    Private Viewholderleft left;    Private Viewholderright right;    Number of layouts private final int view_type = 2;    0 for sending private final int type_0 = 0;    1 for accepting private final int type_1 = 1;        Public Adapter (list<bean> lists,context Context) {this.lists = lists;    This.context = context;    } @Override public int getcount () {return lists.size ();    } @Override public Object getItem (int position) {return lists.get (position); } @Override PublicLong Getitemid (int position) {return position; }/** * describes this method. This method is called when each view is called, obtaining the currently required view style * @param position * @return */@Override public int Getitemviewtype ( int position) {return (Lists.get (position). Getflag () = = Bean.send)?    Type_0:type_1;    }/** * Returns the layout type * @return */@Override public int getviewtypecount () {return view_type;        } @Override public View getView (int position, view Convertview, ViewGroup parent) {left = null;        right = NULL;        Inflater = Layoutinflater.from (context);       int tpye = Getitemviewtype (position);        System.out.print (tpye+ "ddd");                    Initialize the layout if (Convertview = = null) {switch (Tpye) {//0 to send case TYPE_0:                    Convertview = Inflater.inflate (r.layout.rightitem,null);                    right = new Viewholderright (); Right.rtextview = (TextView) Convertview.findviewbyid (R.ID.ID_TV);                    Right.rtime = (TextView) Convertview.findviewbyid (r.id.id_time);                    Right.riv = (circularimage) Convertview.findviewbyid (R.ID.ID_IV);                    Convertview.settag (right);                Break                    1 for accepting case Type_1:convertview = inflater.inflate (r.layout.leftitem,null);                    left = new Viewholderleft ();                    Left.ltextview = (TextView) Convertview.findviewbyid (R.ID.ID_TV);                    Left.ltime = (TextView) Convertview.findviewbyid (r.id.id_time);                    Left.liv = (circularimage) Convertview.findviewbyid (R.ID.ID_IV);                    Convertview.settag (left);            Break }}else{switch (Tpye) {//0 for sending case type_0:right = (Vi                    Ewholderright) Convertview.gettag ();                Break 1 for receiving               Case type_1:left = (viewholderleft) convertview.gettag ();            Break                }}/** * Set the resource for each layout */switch (Tpye) {//0 to send case TYPE_0:                Right.rtextView.setText (Lists.get (position). GetContent ());                Right.rtime.setText (Lists.get (position). GetTime ());                Right.riv.setImageResource (R.drawable.youtouxiang);                Break                1 for receiving case TYPE_1:left.ltextView.setText (Lists.get (position). GetContent ());                Left.ltime.setText (Lists.get (position). GetTime ());                Left.liv.setImageResource (R.drawable.zuotouxiang);        Break    } return Convertview;        }//Left buffer class viewholderleft{TextView Ltextview;        TextView Ltime;    Circularimage Liv;        }//Right buffer class static classes viewholderright{TextView Rtextview; TextView Rtime;    Circularimage Riv; }}

GetviewtypecountThe method is to return the number of layouts we have;The Getitemviewtype method is based on the position of the data to determine which layout we need to choose, so the logic of this method needs to be implemented by itself.
the rest of the operation is basically the same as the ListView optimization operation. First determine whether Convertview is empty, empty is initialized holder, different to get the corresponding flag holder, and finally fit the data into the good.
to the beginning, the whole Turing man's development is basically over.
csdn Project Download link: Turing man download linkGitHub Project Link: Turing man github link









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

Introduction to low threshold--Turing robot development

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.