Development of the ListView for Android Hodgepodge Project 2 and Data Warehouse development model

Source: Internet
Author: User

Today is the first day of work after the fake, in order to prove that I am not a phantom code, I give you spectators Master said: I wish you a happy holiday (not happy that is human).

We continue to talk about the development of the ListView, the last time we talked about the ListView adapter and layout mode, today is about simple but also applicable click event Processing. Before our interface is to talk to the robot, the object is always only a robot, this time we have to imitate the QQ message interface with a list of objects, click on one of them can enter the corresponding chat interface. Words not much to say, first on the code:

Add a layout file Activity_chatlist.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:o rientation= "Horizontal" >    <imageview        android:id= "@+id/iv_chatlist_icon"        android:layout_width= "40DP"        android:layout_height= "40DP"        android:layout_marginleft= "@dimen/activity_vertical_margin"/>    <textview        android:id= "@+id/tv_chatlist_account"        android:layout_width= "Wrap_content        " android:layout_height= "Match_parent"        android:layout_marginleft= "@dimen/activity_vertical_margin"        android:gravity= "center"        android:textsize= "@dimen/mid_text_size"/></linearlayout>
Two new Java files added Chatactivity.java

Package Com.teachmodel.fragment;import Android.app.activity;import Android.content.intent;import android.os.Bundle ; Import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.listview;import Com.teachmodel.r;import Com.teachmodel.adapter.chatadapter;import Com.teachmodel.bean.chat;import java.util.arraylist;import java.util.hashtable;import java.util.List;/** * Created by Windbreaker on 16/4/5.    */public class Chatactivity extends Activity {private ListView mlistview;    Private list<chat> mlist;    Private Chatadapter Mchatadapter;    Private hashtable<string, string> anschats;    Private EditText Et_chat;    Private Button Btn_chat;    Private String Chatname;    private int Chaticon;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.fragment_first);    Init ();     } private void Init () {Intent Intent = getintent ();   Chatname = Intent.getstringextra ("account");        Chaticon = Intent.getintextra ("icon", 0);        Et_chat = (EditText) Findviewbyid (r.id.et);        Btn_chat = (Button) Findviewbyid (R.ID.BTN);        Mlistview = (ListView) Findviewbyid (r.id.lv_chat_list);        Mlist = new arraylist<> ();        Anschats = new hashtable<> ();        Anschats.put ("Hi", "Hello");        Anschats.put ("What's your name?", "My name is DuBe."); Anschats.put ("What?")        Doubi? "," Yeah ... ");        Anschats.put ("Ha...,how interesting", "Thank you.");        Mchatadapter = new Chatadapter (mlist, this);        Mlistview.setadapter (Mchatadapter);                Btn_chat.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Chat mchat = new Chat ();                Mchat.setname ("White Horse Autumn Wind");                Mchat.seticon (r.mipmap.my);                Mchat.setmessage (Et_chat.gettext (). toString ()); Mchatadapter.additem (Mchat);                Getans (Et_chat.gettext (). toString ());            Et_chat.settext ("");    }        });        private void Getans (String question) {chat mchat = new Chat ();        Mchat.setname (Chatname);        Mchat.seticon (Chaticon);        if (anschats.get (question) = null) {Mchat.setmessage (Anschats.get (question));        } else {mchat.setmessage ("I dont know what do you ask?");        } mchatadapter.additem (Mchat);    Mlistview.setselection (Mlistview.getbottom ()); }}

Chatlistadapter.java

Package Com.teachmodel.adapter;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.ImageView ; Import Android.widget.textview;import com.teachmodel.r;import com.teachmodel.bean.chat;import java.util.List;/** * Created by Windbreaker on 16/4/5.    */public class Chatlistadapter extends Baseadapter {private list<chat> chatlist;    Private Layoutinflater Mlayoutinflater;        Public Chatlistadapter (list<chat> chatlist, Context context) {this.chatlist = chatlist;    This.mlayoutinflater = Layoutinflater.from (context);    } @Override public int getcount () {return chatlist.size ();    } @Override public Object getItem (int position) {return chatlist.get (position);    } @Override public long getitemid (int position) {return position; } @Override public view getView (int position, view Convertview, VIEWGRoup parent) {Viewholder mviewholder;            if (Convertview = = null) {Convertview = mlayoutinflater.inflate (r.layout.item_chatlist, NULL);            Mviewholder = new Viewholder ();            MVIEWHOLDER.IV = (ImageView) Convertview.findviewbyid (R.id.iv_chatlist_icon);            Mviewholder.tv = (TextView) Convertview.findviewbyid (R.id.tv_chatlist_account);        Convertview.settag (Mviewholder);        } else {Mviewholder = (Viewholder) convertview.gettag ();        } mViewHolder.tv.setText (Chatlist.get (position). GetName ());        MViewHolder.iv.setImageResource (Chatlist.get (position). GetIcon ());    return convertview;        } class Viewholder {ImageView IV;    TextView TV; }}

Change it again, Firstfragment.java.

Package Com.teachmodel.fragment;import Android.content.intent;import Android.os.bundle;import Android.support.annotation.nullable;import Android.support.v4.app.fragment;import Android.view.LayoutInflater; Import Android.view.view;import Android.view.viewgroup;import Android.widget.adapterview;import Android.widget.listview;import Com.teachmodel.r;import Com.teachmodel.adapter.chatlistadapter;import Com.teachmodel.bean.chat;import java.util.arraylist;import java.util.list;/** * Created by windbreaker on 16/3/23.    */public class Firstfragment extends Fragment {private View V;    Private ListView LV;    Private list<chat> mlist;    Private int[] Iconlab = {r.mipmap.ic_launcher, R.mipmap.usericon, r.mipmap.my};    Private string[] Namelab = {"Robot", "Administrator", "Windbreaker of the Night"}; @Nullable @Override public View oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedin        Stancestate) {v = inflater.inflate (r.layout.activity_chatlist, NULL);    Init ();    InitData ();    return v;        } private void Init () {LV = (ListView) V.findviewbyid (r.id.lv_chatlist); Lv.setonitemclicklistener (New Adapterview.onitemclicklistener () {@Override public void Onitemclick ( Adapterview<?> Parent, view view, int position, long id) {Intent Intent = new Intent (getactivity (),                Chatactivity.class);                Intent.putextra ("Account", mlist.get (position). GetName ());                Intent.putextra ("icon", mlist.get (position). GetIcon ());            StartActivity (Intent);    }        });        } private void InitData () {mlist = new arraylist<> ();            for (int i = 0; i < 3; i++) {chat mchat = new Chat ();            Mchat.setname (Namelab[i]);            Mchat.seticon (Iconlab[i]);        Mlist.add (Mchat);        } chatlistadapter Mchatlistadapter = new Chatlistadapter (mlist, getactivity ());    Lv.setadapter (Mchatlistadapter); }}

Remember to register the new activity component in Androidmanifest.xml: <activity android:name= ". Fragment. Chatactivity "/>

So let's run it and see how it works, see the big screen:


Hmm, this is a glimpse, the effect is good. Let's analyze and analyze the code, the first is to add the last not mentioned in the adapter GetView () this method.

Public View GetView (int position, View Convertview, ViewGroup parent) {
Viewholder Mviewholder;
if (Convertview = = null) {
Convertview = mlayoutinflater.inflate (r.layout.item_chatlist, NULL);
Mviewholder = new Viewholder ();
MVIEWHOLDER.IV = (ImageView) Convertview.findviewbyid (R.id.iv_chatlist_icon);
Mviewholder.tv = (TextView) Convertview.findviewbyid (R.id.tv_chatlist_account);
Convertview.settag (Mviewholder);
} else {
Mviewholder = (Viewholder) convertview.gettag ();
}
MViewHolder.tv.setText (Chatlist.get (position). GetName ());
MViewHolder.iv.setImageResource (Chatlist.get (position). GetIcon ());
return convertview;
}

The first line of code we see this viewholder inner class, what is this class for? This is actually an abstraction of the control in the layout file item_chatlist, where there is a imageview and textview that correspond to the two controls in the layout file. The next code is to check if the View object already exists, and if not, re-instantiate it and then use it directly. That might be more abstract. I would like to make an analogy: Compare the program instructor, the object to be instantiated as a row to register the players. Now instructors know how many people, but do not know how many people have issued identity cards (Viewholder). So he started the roll call, which is the process:

if (Convertview = = null) {
Convertview = mlayoutinflater.inflate (r.layout.item_chatlist, NULL);
Mviewholder = new Viewholder ();
MVIEWHOLDER.IV = (ImageView) Convertview.findviewbyid (R.id.iv_chatlist_icon);
Mviewholder.tv = (TextView) Convertview.findviewbyid (R.id.tv_chatlist_account);
Convertview.settag (Mviewholder);
} else {
Mviewholder = (Viewholder) convertview.gettag ();
}

Tell me if you have a ID card, and I'll send you one.

Mviewholder = new Viewholder ();
MVIEWHOLDER.IV = (ImageView) Convertview.findviewbyid (R.id.iv_chatlist_icon);
Mviewholder.tv = (TextView) Convertview.findviewbyid (R.id.tv_chatlist_account);

This ID card is the sign that I'm going to find you. Convertview.settag (Mviewholder);

After you take it, write your name and avatar.

MViewHolder.tv.setText (Chatlist.get (position). GetName ());
MViewHolder.iv.setImageResource (Chatlist.get (position). GetIcon ());

If you have, the instructor according to the label request you to take out your corresponding identity card I look

Mviewholder = (Viewholder) convertview.gettag ();

And then I'll check your I.D. card information.

MViewHolder.tv.setText (Chatlist.get (position). GetName ());
MViewHolder.iv.setImageResource (Chatlist.get (position). GetIcon ());

It was OK until all the teammates were checked out again.

After talking about how the adapter works, let's talk about how the ListView responds to click Events.

The Click event of the ListView is very simple, just after instantiation (LV = (ListView) V.findviewbyid (r.id.lv_chatlist);) Use this method

Lv.setonitemclicklistener (New Adapterview.onitemclicklistener () {
@Override
public void Onitemclick (adapterview<?> parent, view view, int position, long ID) {
Your code of execution

Intent Intent = new Intent (getactivity (), chatactivity.class);
Intent.putextra ("Account", mlist.get (position). GetName ());
Intent.putextra ("icon", mlist.get (position). GetIcon ());
StartActivity (Intent);
}
});
You can handle the Click event. The position here is the first item of the list you clicked.

In this way, the ListView's explanation is here first. Let's talk about the design pattern of the Data warehouse.

Before we talk about this concept, let's talk about our program, as you can see, all the data in our program is generated in the activity, which means that activity not only defines variables, manages variables, gets controls, handles monitoring events for controls, generates and processes data, manages jump logic , manage its own life cycle and so on. If I let a person deal with these things, I think the person will patience even if he doesn't jump. Similarly, this is not good for the activity, because he manages too many things too miscellaneous. What then? Does it have to be heaven? With the sun side? For this problem, we just need to do a separation of functions, that is, the data generation and processing functions alone, the activity is only responsible for capturing the data set is OK, this is the so-called Data Warehouse design. Not blind force, we come to see the concrete implementation.

Add a new Java file: Chatlab.java

Package Com.teachmodel.bean;import Com.teachmodel.r;import Java.util.arraylist;import java.util.Hashtable;import java.util.list;/** * Created by windbreaker on 16/4/5.    */public class Chatlab {private static Chatlab Mchatlab;    private static list<chat> mlist;    Private hashtable<string, string> anschats;    Private int[] Iconlab = {r.mipmap.ic_launcher, R.mipmap.usericon, r.mipmap.my};    Private string[] Namelab = {"Robot", "Administrator", "Windbreaker of the Night"};        Private Chatlab () {mlist = new arraylist<> ();            for (int i = 0; i < 3; i++) {chat mchat = new Chat ();            Mchat.setname (Namelab[i]);            Mchat.seticon (Iconlab[i]);        Mlist.add (Mchat);        } anschats = new hashtable<> ();        Anschats.put ("Hi", "Hello");        Anschats.put ("What's your name?", "My name is DuBe."); Anschats.put ("What?")        Doubi? "," Yeah ... ");    Anschats.put ("Ha...,how interesting", "Thank you."); } public static Chatlab GetinsTance () {if (Mchatlab = = null) {Mchatlab = new Chatlab ();    } return Mchatlab;    } public list<chat> GetList () {return mlist;    } public hashtable<string, String> Getans () {return anschats; }}

And then modify Firstfragment.java and Chatactivity.java.

Package Com.teachmodel.fragment;import Android.app.activity;import Android.content.intent;import android.os.Bundle ; Import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.listview;import Com.teachmodel.r;import Com.teachmodel.adapter.chatadapter;import Com.teachmodel.bean.chat;import Com.teachmodel.bean.chatlab;import Java.util.arraylist;import java.util.Hashtable ; Import java.util.list;/** * Created by windbreaker on 16/4/5.    */public class Chatactivity extends Activity {private ListView mlistview;    Private list<chat> mlist;    Private Chatadapter Mchatadapter;    Private EditText Et_chat;    Private Button Btn_chat;    Private String Chatname;    private int Chaticon;    Private hashtable<string, string> anschats;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.fragment_first);        Init ();    InitData (); } privatevoid Init () {et_chat = (EditText) Findviewbyid (r.id.et);        Btn_chat = (Button) Findviewbyid (R.ID.BTN);    Mlistview = (ListView) Findviewbyid (r.id.lv_chat_list);        } private void InitData () {Intent Intent = getintent ();        Chatname = Intent.getstringextra ("account");        Chaticon = Intent.getintextra ("icon", 0);        Anschats = Chatlab.getinstance (). Getans ();        Mlist = new arraylist<> ();        Mchatadapter = new Chatadapter (mlist, this);        Mlistview.setadapter (Mchatadapter);                Btn_chat.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Chat mchat = new Chat ();                Mchat.setname ("White Horse Autumn Wind");                Mchat.seticon (r.mipmap.my);                Mchat.setmessage (Et_chat.gettext (). toString ());                Mchatadapter.additem (Mchat);                Getans (Et_chat.gettext (). toString ());            Et_chat.settext (""); }        });        private void Getans (String question) {chat mchat = new Chat ();        Mchat.setname (Chatname);        Mchat.seticon (Chaticon);        if (anschats.get (question) = null) {Mchat.setmessage (Anschats.get (question));        } else {mchat.setmessage ("I dont know what do you ask?");        } mchatadapter.additem (Mchat);    Mlistview.setselection (Mlistview.getbottom ()); }}

Package Com.teachmodel.fragment;import Android.content.intent;import Android.os.bundle;import Android.support.annotation.nullable;import Android.support.v4.app.fragment;import Android.view.LayoutInflater; Import Android.view.view;import Android.view.viewgroup;import Android.widget.adapterview;import Android.widget.listview;import Com.teachmodel.r;import Com.teachmodel.adapter.chatlistadapter;import Com.teachmodel.bean.chat;import com.teachmodel.bean.chatlab;import java.util.list;/** * Created by windbreaker on 16/3 /23.    */public class Firstfragment extends Fragment {private View V;    Private ListView LV;    Private list<chat> mlist; @Nullable @Override public View oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedin        Stancestate) {v = inflater.inflate (r.layout.activity_chatlist, NULL);        Init ();        InitData ();    return v;        } private void Init () {LV = (ListView) V.findviewbyid (r.id.lv_chatlist); Lv. Setonitemclicklistener (New Adapterview.onitemclicklistener () {@Override public void Onitemclick (Ad Apterview<?> Parent, view view, int position, long id) {Intent Intent = new Intent (getactivity (), Ch                Atactivity.class);                Intent.putextra ("Account", mlist.get (position). GetName ());                Intent.putextra ("icon", mlist.get (position). GetIcon ());            StartActivity (Intent);    }        });        private void InitData () {mlist = Chatlab.getinstance (). GetList ();        Chatlistadapter mchatlistadapter = new Chatlistadapter (mlist, getactivity ());    Lv.setadapter (Mchatlistadapter); }}

Run a little bit to get the results. Then some people may ask what is the use of this design pattern? Is it possible to improve the operational efficiency of the program? This may not improve the operational efficiency of the program, but it may also slightly affect your program running efficiency. Speaking of which, you might say I'm a pit-man. To this, I can only say, why there is this design pattern? In fact, all the design patterns of the program are for the convenience of management and programming for the purpose of improving the efficiency of the operation is mainly related to your programming algorithm. For the previous modeless programming, if you only have a few lines of code, there is actually no design mode does not matter. But you have thousands of or even tens of thousands of lines of code, the design pattern is particularly important. Take Data Warehouse as an example, if your program has a lot of places to use the same data, every place to generate and initialize the data, it is better to put the data and the method of calling the data together, the data to be used to directly call the Data warehouse data in the row, you do not have to manage the data. This is very helpful to organize ideas and modify the code.

Today, I would like to thank you all the spectators of the master onlookers.

Project package link Click to open link

Development of the ListView for Android Hodgepodge Project 2 and Data Warehouse development model

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.