Solution of coexistence problem of Android:listview and button

Source: Internet
Author: User

The ListView and other widgets that can trigger click events do not work together because the ItemClick event of the ListView cannot be triggered and is masked by the Click event of other widgets after the addition of other widgets.
    • First, let's explain that each row in the ListView includes the following three items:
A ImageView, a textview, a ImageButton, in turn. The following is the layout of the content, divided into two parts:
    • Res/layout/main.xml
      <?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" Fill_parent "android:layout_height=" Fill_parent "    android: padding= "10dip" android:orientation= "vertical" >    <listview android:id= "@id/android:list" Android: Layout_width= "Fill_parent"        android:layout_height= "Fill_parent"/></linearlayout>

Res/layout/lvitem.xml because the listactivity is inherited, the ListView ID is set to "@id/android:list" is required

Attention:

In the <RelativeLayout>

Android:descendantfocusability= "Blocksdescendants"

and <ImageButton>

Android:focusable= "false"

The setting of these two items is critical, and if not set, will cause the ItemClick event of the ListView to fail to fire, which is masked by the ImageButton click event.

  • <?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:padding= "5dip"android:descendantfocusability= "Blocksdescendants" > <ImageView Android:id= "@+id/itemimage"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:padding= "5dip"/> <!--set the button background to transparent: Android:background= "#00000000"set the background of the button to translucent: Android:background= "#e0000000"-<ImageButton Android:id= "@+id/itemclosewin"Android:layout_alignparentright= "true"Android:layout_aligntop= "@+id/itemwinname"Android:layout_alignbottom= "@+id/itemwinname"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:background= "#e0000000"android:gravity= "Left|center_vertical"android:focusable= "false"android:src= "@android:d rawable/ic_menu_close_clear_cancel"/> <TextView Android:id= "@+id/itemwinname"Android:layout_torightof= "@+id/itemimage"Android:layout_toleftof= "@+id/itemclosewin"Android:layout_aligntop= "@+id/itemimage"Android:layout_alignbottom= "@+id/itemimage"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:gravity= "Left|center_vertical"android:textsize= "20dip"Android:text= "title"/> </RelativeLayout>

    In Lvwithbuttonext, in order to be able to handle the ImageButton click event, I inherited the Baseadapter class and re-implemented the GetView () interface, in which the button's Clicklistener was added, See the implementation of the Lvbuttonadapter class. Next, let's look at the implementation of the inherited Listactivity
 Public classLvwithbuttonextextendslistactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); //ListView in the associated layoutListView Vnclistview =(ListView) Findviewbyid (Android.                R.id.list); //generating dynamic arrays, adding dataarraylist();  for(inti=0;i<10;i++) {HashMap<string, object> map =NewHashmap<string, object>(); Map.put ("Itemimage", R.drawable.firefox);//ID of the image resourceMap.put ("Itemwinname", "Window ID" +i); Map.put ("Itemclosewin", Android.            R.drawable.ic_menu_close_clear_cancel);        Remotewindowitem.add (map); }              //build the adapter's item and the element corresponding to the dynamic arrayLvbuttonadapter Listitemadapter =NewLvbuttonadapter ( This, Remotewindowitem,//Data SourceR.layout.lvitem,//XML implementation of ListItem//the children of the dynamic array corresponding to the Imageitem            NewString[] {"Itemimage", "Itemwinname", "Itemclosewin"},            //imageitem XML file inside of a imageview, two TextView ID            New int[] {r.id.itemimage,r.id.itemwinname,r.id.itemclosewin});    Vnclistview.setadapter (Listitemadapter); } @Overrideprotected voidOnlistitemclick (ListView L, View V,intPositionLongID) {        //TODO auto-generated Method Stub        Super. Onlistitemclick (l, V, position, id);    L.getitematposition (position); }}

    • To respond to a button's Click event, first record the position of the button and then set the Clicklistener for the button. Next, let's look at the implementation of Lvbuttonadapter

In the re-implemented GetView () interface, I used the Lvbuttonlistener listener class, which, in the constructor, records the line number so that it can be positioned exactly where the button is located in the OnClick interface, and the corresponding row is processed.

 Public classLvbuttonadapterextendsBaseadapter {Private classButtonviewholder {ImageView appIcon;        TextView AppName;    ImageButton Buttonclose; }        PrivateArraylistmapplist; PrivateLayoutinflater Minflater; PrivateContext Mcontext; Privatestring[] keystring; Private int[] valueviewid; PrivateButtonviewholder Holder;  PublicLvbuttonadapter (Context C, arraylistintresource, string[] from,int[] to) {Mapplist=applist; Mcontext=C; Minflater=(Layoutinflater) Mcontext.getsystemservice (Context.layout_inflater_service); KeyString=NewString[from.length]; Valueviewid=New int[To.length]; System.arraycopy (From,0, keystring, 0, from.length); System.arraycopy (To,0, Valueviewid, 0, to.length); } @Override Public intGetCount () {returnmapplist.size (); } @Override PublicObject GetItem (intposition) {        returnMapplist.get (position); } @Override Public LongGetitemid (intposition) {        returnposition; }     Public voidRemoveItem (intposition)        {mapplist.remove (position);  This. notifydatasetchanged (); } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {        if(Convertview! =NULL) {Holder=(Buttonviewholder) Convertview.gettag (); } Else{Convertview= Minflater.inflate (R.layout.lvitem,NULL); Holder=NewButtonviewholder (); Holder.appicon= (ImageView) Convertview.findviewbyid (valueviewid[0]); Holder.appname= (TextView) Convertview.findviewbyid (valueviewid[1]); Holder.buttonclose= (ImageButton) Convertview.findviewbyid (valueviewid[2]);        Convertview.settag (holder); } HashMap<string, object> appInfo =Mapplist.get (position); if(AppInfo! =NULL) {String aname= (String) appinfo.get (keystring[1]); intMid = (Integer) appinfo.get (keystring[0]); intBid = (Integer) appinfo.get (keystring[2]);            Holder.appName.setText (Aname);            Holder.appIcon.setImageDrawable (Holder.appIcon.getResources (). Getdrawable (mid));            Holder.buttonClose.setImageDrawable (Holder.buttonClose.getResources (). getdrawable (Bid)); Holder.buttonClose.setOnClickListener (NewLvbuttonlistener (position)); }                returnConvertview; }    classLvbuttonlistenerImplementsOnclicklistener {Private intposition; Lvbuttonlistener (intPOS) {Position=POS; } @Override Public voidOnClick (View v) {intVid=V.getid (); if(vid = =holder.buttonClose.getId ()) RemoveItem (position); }    }}


Click on the right button the row will be deleted the following is run:

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.