Android Basics Getting Started tutorial--2.4.6 ListView Data Update issues
tags (space delimited): Android Basics Getting Started Tutorial
Introduction to this section:
We have learned some basic usage of the ListView before, but careful you may find that our data
Defined at the outset, are static, but in real development, our data is often dynamic, such as
I delete the column, then the list of data should also be synchronized updates, then this section we will discuss
Under the ListView Data Update issue, including all updates, and updating one of these, then start this section! ~
1. Write a normal demo first
OK, first write a normal demo first, wait for us to adjust slowly:
Entity class:Data.java:
/** * Created by Jay on 2015/9/21 0021. * * Public class Data { Private intImgid;PrivateString content; Public Data() {} Public Data(intImgid, String content) { This. Imgid = Imgid; This. Content = content; } Public int Getimgid() {returnImgid; } PublicStringgetcontent() {returnContent } Public void Setimgid(intImgid) { This. Imgid = Imgid; } Public void setcontent(String content) { This. Content = content; }}
activity layout and list item layout :
activity_main.xml:
<linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns:tools =" Http://schemas.android.com/tools " android:layout_width = "match_parent" android:layout_height =" match_parent " android:orientation =" vertical " tools:context =; <ListViewandroid:id="@+id/list_one"android:layout_width="Match_ Parent "android:layout_height=" match_parent " /> </linearlayout>
item_list.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:orientation="Horizontal"> <ImageViewandroid:id="@+id/img_icon"android:layout_width= "56DP" android:layout_height="56DP"/> <TextViewandroid:id= "@+id/txt_content"android:layout_width=" Wrap_content "android:layout_height=" Wrap_content "android:layout_margintop= "20DP"android:layout_marginleft="10DP"android:textsize="18sp" /> </linearlayout>
Custom Baseadapter implementation:Myadapter.java:
/** * Created by Jay on 2015/9/21 0021. * * Public class myadapter extends baseadapter { PrivateContext Mcontext;PrivateLinkedlist<data> Mdata; Public Myadapter() {} Public Myadapter(linkedlist<data> mdata, Context mcontext) { This. Mdata = Mdata; This. Mcontext = Mcontext; }@Override Public int GetCount() {returnMdata.size (); }@Override PublicObjectGetItem(intPosition) {return NULL; }@Override Public Long Getitemid(intPosition) {returnPosition }@Override PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {Viewholder Holder =NULL;if(Convertview = =NULL) {Convertview = Layoutinflater.from (Mcontext). Inflate (R.layout.item_list,parent,false); Holder =NewViewholder (); Holder.img_icon = (ImageView) Convertview.findviewbyid (R.id.img_icon); Holder.txt_content = (TextView) Convertview.findviewbyid (r.id.txt_content); Convertview.settag (holder); }Else{holder = (Viewholder) convertview.gettag (); } holder.img_icon.setImageResource (Mdata.get (position). Getimgid ()); Holder.txt_content.setText (Mdata.get (position). GetContent ());returnConvertview; }Private class viewholder{ImageView Img_icon; TextView txt_content; }}
Mainactivity.java 's writing:
Public class mainactivity extends appcompatactivity { PrivateListView List_one;PrivateMyadapter Madapter =NULL;PrivateList<data> Mdata =NULL;PrivateContext Mcontext =NULL;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Mcontext = mainactivity. This; Bindviews (); Mdata =NewLinkedlist<data> (); Madapter =NewMyadapter ((linkedlist<data>) mdata,mcontext); List_one.setadapter (Madapter); }Private void bindviews() {List_one = (ListView) Findviewbyid (R.id.list_one); }}
Can run, after the run found that our page does not have any data, the whiteness of a piece, such a user experience is not good,
we can call the ListView of a Setemptyview (View) method, When the ListView data is empty,
displays a corresponding view, and found that the method is very wonderful, the dynamic addition of view, unexpectedly invalid, can only be in the ListView
in the layout file to add when the ListView does not have data, you want to display the view, In addition with this Setemptyview set after the
View, load the time unexpectedly will not show out, good supernatural .... For example, here is a textview with no data displayed without data
, and some of the code is as follows:
<textview android:id=" @+id/txt_empty " android:layout_width=" wrap_content " android:lay Out_height= "wrap_content" android:layout_gravity= " Center " Android:textsize=" 15pt " android:textcolor=" #000000 "/> txt_empty = (TextView) Findviewbyid (R.id .txt _empty) txt_empty.settext ( "no Data ~" ) List_one.setemptyview (txt_empty)
Of course, in addition to this method, we can define a layout that is the same size as the ListView, and then set the
Android:visibility= "Gone", in Java code to determine the size of the Mdata collection, if ==0,
Description No data, let this layout show, when there is data to let this layout hidden ~
2. Add a record
All right, let's get a button. Add a record without pressing one at a time ha ~
Run :
Code implementation
Define a method in our custom Baseadapter, with the following methods:
publicvoid add(Datadata) { if==null) { =new LinkedList<>(); } mData.add(data); notifyDataSetChanged(); }
The layout then adds a button, then sets the next event, the code is as follows:
private Button btn_add; btn_add = (Button) findViewById(R.id.btn_add); btn_add.setOnClickListener(this); @Override publicvoidonClick(View v) { switch (v.getId()){ case R.id.btn_add: mAdapter.add(new Data(R.mipmap.ic_icon_qitao,"给猪哥跪了~~~ x " + flag)); flag++; break; } }
Hey, become, add data is so simple ~, if you want to insert into a specific location, also line, we adapter class, and then another
Write a method:
//往特定位置,添加一个元素 publicvoidadd(int position,Data data){ ifnull) { new LinkedList<>(); } mData.add(position,data); notifyDataSetChanged(); }
Then add a button to write an event:
private Button btn_add2; btn_add2 = (Button) findViewById(R.id.btn_add2); btn_add2.setOnClickListener(this); case R.id.btn_add2: //position从0开始算的 mAdapter.add(4,new Data(R.mipmap.ic_icon_qitao,"给猪哥跪了~~~ x " + flag)); break;
Run :
You can see that our Nineth item is inserted into the fifth position ~
3. Delete an item
Similarly, we write two methods, one to delete the object directly, and one to delete it according to the cursor:
publicvoidremove(Data data) { ifnull) { mData.remove(data); } notifyDataSetChanged(); } publicvoidremove(int position) { ifnull) { mData.remove(position); } notifyDataSetChanged(); }
Then add two buttons to invoke the next two methods:
case R.id.btn_remove: mAdapter.remove(mData_5); break;case R.id.btn_remove2: mAdapter.remove(2); break;
Run :
We can see that the fifth item is removed, and then click on the cursor to delete the data, the third item has been deleted!
4. Remove all records:
This is even simpler, call the Clear method directly! The method code is as follows:
publicvoidclear() { ifnull) { mData.clear(); } notifyDataSetChanged(); }
5. Update a record
Careful you should find, after the data modification operation, will call a notifydatasetchanged ();
At first I thought:
Notifydatasetchanged () redraws the actual item on the interface once, which can affect UI performance, if the amount of data
It's big, but I'm going to have to re-draw all the items when I change one, which is definitely unreasonable. So, I used a stupid way.
To modify the value of a control in an item, I wrote a piece of code in the Java code:
private void Updatelistitem (int postion,data mdata) {int visibleposition = List_one. Getfirstvisibleposition();View v = list_one. Getchildat(postion-visibleposition);ImageView img = (ImageView) v. Findviewbyid(R. ID. IMG_icon);TextView TV = (TextView) v. Findviewbyid(R. ID. txt_content);Img. Setimageresource(Mdata. Getimgid());Tv. SetText(Mdata. GetContent());}
later with the group of friends to discuss the next, found himself wrong :
The Notifydatasetchanged () method will determine if it needs to be re-rendered if the current item does not need to be re-rendered
is not re-rendered, if the state of an item changes, it will cause the view to redraw, and the redraw is not
All item, but the item! that the view state has changed So we directly Notifydatasetchange () method
Can, of course, know one more of the above method is nothing ~
Code Download:
Listviewdemo3.zip
This section summarizes:
OK, this section tells you about the implementation of the data update in the ListView, of course, not only the ListView, but the other adapter
Class controls can call these methods to complete data updates ~ That's all there is to it ~ Thank you
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Basics Getting Started tutorial--2.4.6 ListView Data Update issues