Uncover traps to dynamically add deleted Items on ListView Adapterview _android

Source: Internet
Author: User
Tags gettext

How to avoid the ListView and other Adapterview on the dynamic add deletion of the trap, below for everyone to share, the specific content as follows

First, define the following array resource as the loading content for the list:

<resources>
 <string name= "app_name" >MyListView</string>
 <string-array name= " Language ">
 <item>Java</item>
 <item>C</item>
 <item>c++</item >
 <item>PHP</item>
 </string-array>

Then simply write down the layout file, because I need to set the Layout_weight in the ListView to 1, regardless of how long the list is, and always display the edit box and button at the bottom.

<?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= "Vertical" >
 <listview
 android:id= "@android: Id/list" android:layout_width= "Fill_
 Parent "
 android:layout_height=" 0dip "
 android:layout_weight=" 1 "/>
 <linearlayout
 Android:layout_width= "Wrap_content"
 android:layout_height= "wrap_content"
 android:orientation= " Horizontal ">
 <edittext
  android:id=" @+id/addlangedit "
  android:layout_width=" 200px
  " android:layout_height= "Wrap_content"/>
 <button 
  android:id= "@+id/addbutton"
  android:layout _width= "Wrap_content"
  android:layout_height= "wrap_content"
  android:text= "add"/>
 </ Linearlayout>
</LinearLayout>

Finally add the activity code, it seems that there is no problem, run it.

public class Mylistview extends Listactivity {private arrayadapter<charsequence> madapter;
 Private ListView Mlistview;
 Private EditText Mlanguagetext;
 
 Private Button Maddbutton; /** called the activity is a.
 * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 
 Setcontentview (R.LAYOUT.MYLIST1);
 Get the View Mlistview = Getlistview ();
 Mlanguagetext = (edittext) Findviewbyid (R.id.addlangedit);
 
 Maddbutton = (Button) Findviewbyid (R.id.addbutton); Array adapter created from string array to Madapter = Arrayadapter.createfromresource (This, R.array.langua GE, Android.
 R.layout.simple_list_item_1);
 
 Set the adapter mlistview.setadapter (Madapter);
 Add Listener Maddbutton.setonclicklistener (Monclicklistener); Private Onclicklistener Monclicklistener = new View.onclicklistener () {@Override public void OnClick (View v) {S
  Tring Text = Mlanguagetext.gettext (). toString ();if (null = = text | |
  "". Equals (Text.trim ()) {Toast.maketext (mylistview.this, input cannot be empty, toast.length_short). Show ();
  }else {madapter.add (text);
  Madapter.notifydatasetchanged ();
  Mlanguagetext.settext ("");
}
 }
 }; }


Interface successful display, but each click "Add", will throw java.lang.UnsupportedOperationException, this seems very strange, because according to the Android API document, indeed through the adapter on the Add, Remove and other methods in the runtime to delete the list items Ah, the problem in the end is where?

With Google Help, find the following answer:

  

Here, if you want to dynamically change the size of a list, you must use a variable-size list (such as ArrayList) instead of a fixed-length array, or you will get unsupportedoperationexception. That is, because the content needs to be loaded from the resource file, I naturally think of calling Arrayadapter.createfromresource (context context, int textarrayresid, int Textviewresid) method to construct adapter, which causes a fixed-length array to be maintained in Arrayadapter! Add to the array, and of course it goes wrong. See here I can't help feeling, a trap!!! The truth seems to be getting closer to me, let's go into the arrayadapter source.

public class Arrayadapter<t> extends Baseadapter implements filterable {//representing data in Arrayadapter private list<
 T> mobjects; Other fields public arrayadapter (context, int textviewresourceid, list<t> objects) {init (context, TEXTVI
 Ewresourceid, 0, objects); Arrayadapter (context context, int Textviewresourceid, t[] objects) {//Note the arrays.aslist here (...)
 Method!!! 
 Init (context, Textviewresourceid, 0, Arrays.aslist (objects)); public static arrayadapter<charsequence> Createfromresource (context context, int textarrayresid, int textviewr
 ESID) {charsequence[] strings = Context.getresources (). Gettextarray (TEXTARRAYRESID);
 Return to new arrayadapter<charsequence> (context, textviewresid, strings); 
 private void init (context context, int resource, int textviewresourceid, list<t> objects) {mcontext = context;
 Minflater = (layoutinflater) context.getsystemservice (Context.layout_inflater_service); Mresource = Mdropdownresource =Resource
 Mobjects = objects;
 Mfieldid = Textviewresourceid;
  public void Add (T object) {if (moriginalvalues!= null) {synchronized (Mlock) {Moriginalvalues.add (object);
  if (Mnotifyonchange) notifydatasetchanged ();
  } else {Mobjects.add (object);//If the mobjects is a fixed-length list, the exception is thrown!!!
 if (Mnotifyonchange) notifydatasetchanged ();
 }//Other methods}


Through the source can be found, I think the above is still wrong. Instead of maintaining the array-type data separately, the Arrayadapter is unified into a list and has a Mobjects object.

Createfromresource (...) The Arrayadapter (context, int Textviewresourceid, t[] objects) Construction method was invoked, and in the internal implementation of the method, Android used the arrays static method Aslist ( ...) Converts an array to a list. Programmers familiar with Java know that arrays.aslist (...) method returns is not a java.util.ArrayList, but a arrays class of the internal class, the list implementation is not allowed to delete operations!! (see JDK documentation), add to the list throws unsupportedoperationexception!

Haha, this is finally the truth, so a little change to the original code can be successfully run: D
FInal Solution:

/** * * * @author Codingmyworld * 2011-7-31 pm 04:43:48/public class Mylistview extends Listactivity {private Arra
 Yadapter<charsequence> Madapter;
 Private ListView Mlistview;
 Private EditText Mlanguagetext;
 
 Private Button Maddbutton; /** called the activity is a.
 * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 
 Setcontentview (R.LAYOUT.MYLIST1);
 Get the View Mlistview = Getlistview ();
 Mlanguagetext = (edittext) Findviewbyid (R.id.addlangedit);
 
 Maddbutton = (Button) Findviewbyid (R.id.addbutton); 
  Array adapter created from string array list<charsequence> objects = new Arraylist<charsequence> (
 Arrays.aslist (Getresources (). Gettextarray (R.array.language))); Madapter = new Arrayadapter<charsequence> (this, Android.
 R.layout.simple_list_item_1, objects);
 
 Set the adapter mlistview.setadapter (Madapter); Add Listener Maddbutton.setonclicklistener (Monclicklistener); Private Onclicklistener Monclicklistener = new View.onclicklistener () {@Override public void OnClick (View v) {S
  Tring Text = Mlanguagetext.gettext (). toString (); if (null = = text | |
  "". Equals (Text.trim ()) {Toast.maketext (mylistview.this, input cannot be empty, toast.length_short). Show ();
  }else {madapter.add (text); Madapter.notifydatasetchanged ();
  Not required Mlanguagetext.settext ("");
}
 }
 };
 }

Above is about the Android ListView related content Introduction, hope to be helpful to everybody's study.

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.