Android ListView Onitemlongclick and Onitemclick event internal details sharing and several more special attributes

Source: Internet
Author: User

This article goes from http://blog.sina.com.cn/s/blog_783ede030101bnm4.html author kiven

Resignation 3, 4 months at home rest, this thought building main programmer reverse attack, the result failed to continue code farming career today began to update blog.

Body. There is a ListView content in the project more complex now to add long press DELETE feature. The landlord naturally thought of using the Onitemlongclick event to deal with the ListView. The results can be imagined in the actual experience is very bad, there will be failure some options to trigger Onitemlongclick events some but did not respond. The landlord to go online to see is focusable to set to false. But in accordance with the landlord experience this can only be solved can not trigger Onitemlongclick event problems, such as the landlord encountered some can be some failure of the estimate is not a dose of medicine.    Therefore, the landlord concrete analysis of the internal details, hoping to provide some help to later people. First look at the foucsable caused by the incident did not respond to the problem.
Reason:If you have a button or a checkbox in your item, the focus is given to these child controls by default, and the ListView item can be selected based on its ability to get focus, so We can set the Focusable property of all controls contained in the item in the ListView to False so that the ListView item automatically gets the focus's permission, and it can be selected. It also responds to the Onitemclick () method in Onitemclicklistener. Workaround:(The following two ways can be any one) 1. Set all child controls in the ListView's item Layout focusable property to False2. Set the property of the root control for item layout (recommended lightweight especially to modify someone else's code)android:descendantfocusability= "Blocksdescendant" so that the item layout blocks all child controls from gaining focus and does not need to target the item Each control in Layout re-sets the Focusable property analysis: Why not set focusable to false will not trigger the Onitemlongclick event. By looking at the source code of the Abslistview, you will find that if focusable is not false, the touch event will not be distributed. The code is as follows:

A brief analysis of the use of android:descendantfocusability in the development of a very common problem, the ListView in the project is not only simple text, often need to define their own ListView, their own adapter to inherit Baseadapter , as required in adapter, the problem arises and there may be no response at the time of clicking on each item, and the focus cannot be obtained. This is mostly due to the presence of child controls such as Imagebutton,button,checkbox in your own definition, such as the child control of a Button or checkable, in which the child controls get the focus.    So often when clicking on item changes the child control, the item itself's click does not respond. This time you can use descendantfocusability to solve, the API description is as follows:
This property is defined as the relationship between ViewGroup and its child controls when one gets the focus for the view. There are three values for the property: Beforedescendants:viewgroup takes precedence over its subclass control and gets to focus Afterdescendants:viewgroup gets the focus only if its subclass control does not need to get focus BL Ocksdescendants:viewgroup overrides the subclass control and gets the focus directly. Usually we use the third type, which is the root layout of the item layout plus android:descendantfocusability= " Blocksdescendants "The properties of the actual situation according to the above set the landlord's problem is still not resolved, the landlord firmly believe that the authority of the above article, re-analysis of their own code. Found in adapter Convertview is set clickable to true (another colleague in order to block item's yellow selector setting of the landlord will introduce modified ListView click Yellow Background Modification) This will inevitably cause the touch event to be intercepted by Convertview, since Convertview is the root container for item, so it is not possible to click into the ListView to get the ListView to capture the touch event. Remove the item and container's clickable settings. Sure enough to trigger the Onitemlongclick event. Failure to solve the problem found in the content of a few simple items is not a problem, but in the complex item when the child view of the item is unavoidable to set the Click event, and this view is the most part of the item, You can't trigger a Onitemlongclick event by pressing and long pressing the item's small spare place every time. Landlord here to give a relatively lightweight solution. The code snippet is as follows://adapter Internal code://hoLder.audiopanel This view occupies a large place but must implement the Click event, fortunately it has Longclick eventsHolder.audioPanel.setOnClickListener (this);Holder.audioPanel.setOnLongClickListener (this);//Key here manually triggering the ListView's long-press method naturally comes back to normal logic. @Overridepublic boolean Onlongclick (View v) {Mlistview.performlongclick (); return false;} This perfectly solves the triggering Onitemlongclick event regardless of how complex the ListView interface is. How to remove the default yellow background for the ListView. The landlord is such a solution:

  Appendix the landlord on the Internet to see some small details: 1. Could the ListView itself call Setonclicklistner ()?   code is possible, but running immediately throws an exception, so it is not possible to intercept the Click event of the ListView itself. When will the  2.listview.setonitemclicklistener set listener be called?   When clicked on a line of content is called, but if this line contains Button,imgbutton and other controls, it will not be called, why and how to resolve see later. When is the listener of  3.listview.setonitemlongclicklistener set called?   is called when a row is long pressed, and has been called before it is lifted.  4. Will the click be called after receiving the Longclick call?   This depends on the return value of the Longclick listener. Java Code  1.lv.setonitemlongclicklistener (new Onitemlongclicklistener () {  2.             public Boolean Onitemlongclick (adapterview<?> parent, View view, int position, long id) { 3.                 system.out.println ("Item LONG clicked. Position: "+ Position);   4.                return false;   5.            }   6.        });   If the return is False then click will still be called. Also, call long click First and then call click.   If True then click is eaten and click is no longer called.  5. Listener Click and long click Affect pop-up menu?  click does not affect; Long Click Returns True then the Click event is eaten, causing the menu to not pop up.    Appendix: Android Using the ListView should be aware of the place in the ListView setting selector to NULL to report null pointers?  mlistview.setselector (null);//null pointer   Try this:  mlistview.setselector (New Colordrawable ( color.transparent);   How do I select an item when the ListView is initialized?  listview needs to be selected when the data is initialized. The so-called "selected state" is that the color is different from other items, setselection (position) can only navigate to an item, but can not change the background is highlighted. SetSelection (position) can only have one item displayed on top of the visible item (if item exceeds one screen)! is the so-called Firstvisibleitem!   If you want to achieve the effect, you can do some specific work in the GetView function in the adapter that the ListView binds to. You can write down the index of the item you want to highlight, and in the GetView function, Judge Index (that is, position) and load a different background if the condition is met.   listview How to enable the right-hand scroll slider?       Many developers do not know how the quick scroll slider of the ListView list control is enabled, in fact the auxiliary scroll slider only needs a single line of code to get it done, If you use an XML layout, you only need to add the  android:fastscrollenabled= "true" attribute to the ListView node, and for Java code can pass mylistview.setfastscrollenabled (true); To control enable, the parameter false is hidden.       Another point is that when you have a small scrolling content that does not appear on the 3 screen height of the current listview, the Fast scroll slider is not present, and the method is the base method of Abslistview. You can use fast scrolling assist in subclasses such as the ListView or GridView.   1. Update the numbers in the ListView by using the Baseadapter notifydatasetchanged () method:        Madapter.notifydatasetchanged ();   2. Each ListView has an inefficient position, such as the first row in the line, the last line in the last row, and this inefficient position is a constant.       listview.invalid_position   3. Sometimes we need to use the Click button in the program to control the selection of the ListView row, which uses the code in the program to select the ListView item .           mlistview.requestfocusfromtouch ();           mlistview.setselection (int index);        The first sentence is not required, but if you have a button in the ListView, Radiobutton,checkbox The first sentence is what you have to add when you have a control that has a higher priority than the ListView.   4.   The ListView's Setonitemclicklistener is not executed if you have a ListView that contains Button,radiobutton,checkbox and other controls that have a higher priority than the ListView., you need to add  android:focusable= "false" to these controls in your XML file. Note that this language is modified in an XML file and is not valid for use in the code.   5. How to keep the scroll bars of the ListView always showing, not hidden: The  xml file is modified as follows    android:fadescrollbars= "false"   6. The ListView itself has its own key event, that is, you do not need to set the direction key of the consciousness, press the key to the ListView will have the action, that how to control, to write their own onkey, you need to re-write in the activity dispatchkeyevent ( KeyEvent event); method, define your own motion here.   listview Custom scroll bar style:  <listview android:id= "@android: Id/list"          android:layout_width= "Match_parent"           android:layout_height= "0dip"           android:layout_weight= "1"          android: Stackfrombottom= "true"//show entries from the beginning          android:transcriptmode= " Normal "         android:fastscrollenabled=" true "          andRoid:focusable= "true"          android:scrollbartrackvertical= "@ Drawable/scrollbar_vertical_track "         android: Scrollbarthumbvertical= "@drawable/scrollbar_vertical_thumb"  /> //scrollbar_vertical_track, Crollbar_vertical_thumb custom XML file, placed in drawable, track refers to the long bar, thumb refers to the short strip   Remove the ListView selector selection of yellow shading of the effect of a flash:   xml Code   <?xml version= "1.0" encoding= "Utf-8"?>  <shape xmlns:android= "/http Schemas.android.com/apk/res/android ">      <solid android:color=" @android: color/ Transparent "/>      <corners android:radius=" 0dip "/>       </shape>  //listview.setselector (R.drawable.thisshape);    or there is a way to rewrite the public boolean isenabled (int position) method in the adapter, and return it to false, it is recommended to use this approach, see HTTP////:  Gundumw100.iteye.com/admin/blogs/850654  java Code   public boolean isenabled (int position) {     //TODO auto-generated method Stub   & Nbsp;  return false;  }    listview Some of the more special properties   First is the Stackfrombottom property, which is only after the list that you do well displays the bottom of your list, with a value of true and False  android:stackfrombottom= "true"                Second is the Transciptmode property, which needs to be tracked or viewed in real time with a ListView or other control that displays a large number of items, and you want the latest entries to automatically scroll to the viewable range. By setting the Control Transcriptmode property, you can automatically slide the controls on the Android platform (support ScrollBar) to the bottom.  android:transcriptmode= "Alwaysscroll"      third Cachecolorhint attribute, many people want to be able to change its background, Enable him to conform to the overall UI design, change the background is very simple only need to prepare a picture and then specify the properties android:background= "@drawable/bg", but do not be happy too early, when you do so, found that the background is changed, but when you drag, Or click on the list blank position to find that the ListItem have become black, destroying the overall effect.   If you just change the color of the background, you can specify Android:cachecolorhint as the color you want, if you are using a picture to do the background, then just specify the android:cachecolorhint as transparent (# 00000000) on the    fourth divider property, the function is to set a picture between each item as an interval, or to remove the split line between item android:divider= "@drawable/list_ Driver "  where   @drawabLe/list_driver is a picture resource, if you do not want to display the split line, as long as the set to Android:divider= "@drawable/@null" can be    fifth Fadingedge property, There is a black shadow on the top and bottom android:fadingedge= the "none" setting does not have a shadow after the ~   fifth ScrollBars property, the function is to hide the scroll bar of the ListView, android:scrollbars= " None "with setverticalscrollbarenabled (true); the effect is the same, not active when hidden, active when also hidden    sixth Fadescrollbars properties, Android: Fadescrollbars= "true"   when configuring the ListView layout, setting this property to True enables the auto-hide and display of scroll bars.    How do I use gallery to drag in flinging without a selection?   This time need to be aware of using  gallery.setcallbackduringfling (false)    How to let the ListView automatically scroll?   Note Both the Stackfrombottom and Transcriptmode properties. The low end of a market-like client keeps rolling.  <listview android:id= "LISTCWJ"       android:layout_width= "Fill_parent"       android:layout_height= "Fill_parent"        Android:stackfrombottom= "true"         android:transcriptmode= " Alwaysscroll " />  How do I traverse the single box of a ListView?   java Code   listview liStview = (ListView) Findviewbyid (the ID of the ListView in the R.id. config file);  //Select the option to traverse the ListView, each option equivalent to the Relativelayout  for in the layout profile (int i = 0; i < Listview.getchildcount (); i++) {        view View = Listview.getchildat (i);        checkbox cb = (CheckBox) View.findviewbyid (R.ID.CHECKBOXID);        cb.setchecked (TRUE); &NBSP:    How do i make the font color of TextView in the ListView follow the change in focus?   We usually need to select one of the items in the ListView, and his font color is different from the original one. How do I set the color of a font? TextColor an item in the layout file to set the color, but instead of just setting a color, you can set different colors under different conditions: Here's an example:   xml code   <?xml version= "1.0" encoding= "Utf-8"?>  <selector xmlns:android= "http://schemas.android.com/apk/res/android" >   <item android:state_enabled= "false" android:color= "@color/orange" ></item>  <item android:state _window_focused= "false" android:color= "@color/orange" ></item>  <item android:state_pressed= "true "Android:color=" @color/whiTE "></item>  <item android:state_selected=" true "android:color=" @color/white "></item>  <item android:color= "@color/orange" ></item>  </selector>    Set to white when the focus is taken or selected, and other cases are set to orange.    How do I customize split lines between the rows of a ListView?   All widget controls that are based on the ListView or Abslistview implementation can set the line spacing split line by using the following method, and the split line can customize the color, or picture.   In the ListView we use the attribute android:divider= "#FF0000" to define the delimiter to be red, of course here the value can point to a drawable picture object, if the use of the picture may be higher than the system default pixels, You can set your own height such as 6 pixels android:dividerheight= "6px", of course, in Java, the ListView also has the relevant method can be set.   listview the specified Item listview not through notifydatasetchanged () is typically updated by notifydatasetchanged () to the ListView, But by notifydatasetchanged () the actual item on the interface is redrawn once, which affects UI performance.   can improve efficiency by updating the specified item, pseudo-code as follows:   java code   private void Updateview (int itemIndex) {      int visibleposition = Yourlistview.getfirstvisibleposition ();      view v = yourlistview.getchildat (itemindex-visibleposition);//Do something fancy with YouR ListItem View      textview TV = (TextView) V.findviewbyid (R.id.sometextview);    tv.settext ("hi! I updated you manually ");  }  

 

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.