Android completely conquer the ListView one (utility article)

Source: Internet
Author: User

ListView Usage Tips

For Android Development, I believe that the ListView control people will not be unfamiliar, its importance is self-evident, its function is complex, in the project of the form of flexible and changeable, to be handy to use not and easy, today led everyone to enjoy the style of the ListView.

1. Using Viewholder
 @Override     PublicViewGetView(intI, view view, ViewGroup viewgroup) {Viewholder holder;if(view==NULL) {holder=NewViewholder (); View=minflater.inflate (R.layout.viewholdernotifyadapter,NULL);            Holder.img= (ImageView) View.findviewbyid (R.id.imageview);            Holder.title= (TextView) View.findviewbyid (R.id.textview);        View.settag (holder); }Else{holder= (Viewholder) View.gettag ();        } holder.img.setImageResource (R.mipmap.ic_launcher); Holder.title.setText (Mdata.get (i));returnView } Public Final  class viewholder{        PrivateImageView img;PrivateTextView title; }
2. Set up divider lines between projects
android:divider="@android:color/darker_gray"//设置分割线android:dividerHeight="10dp"//设置分隔线高度android:divider="@null"//隐藏分割线
3. Hide the ListView scroll bar
android:scrollbars="none"//隐藏ListView滚动条
4. Cancel the ListView item click Effect
android:listSelector="@android:color/transparent"//取消ListView的Item点击效果
5. Set the ListView to be displayed in the first item
listView.setSelection(N);//默认显示在第N个Item,(N为第N个Item)(瞬时完成)//平滑移动mListView.smoothScrollBy(distance,duration);mListView.smoothScrollByOffset(offset);mListView.smoothScrollToPosition(index);
6. Dynamically Modify the ListView

Use Adapter.notifydatasetchanged (); notify the ListView to change the data source to the ListView dynamic modification, you must ensure that the incoming adapter data list is the same list and cannot be other objects, otherwise the effect cannot be achieved

publicvoidbtnAddItem(View view){        mData.add("哈哈哈");        adapter.notifyDataSetChanged();//通知Adapter更新数据        listView.setSelection(mData.size()-1);    }
7. Traverse all the item in the ListView

Get the Sub View by Getchildat ().

for (int0; i < listView.getChildCount(); i++) {            View view = listView.getChildAt(i);        }
8. Handling Empty ListView

Show default prompts with Setemptyview (), Liseview without data

 <framelayoutandroid:layout_width="Match_parent"android:layout_height ="0DP"android:layout_weight="1">                                <ListViewandroid:id="@+id/listview"android:layout_width="Match_ Parent "android:layout_height=" Match_parent "android:divider=" @android: Color /darker_gray "android:dividerheight=" 10DP "android:listselector=" @ Android:color/transparent "android:scrollbars=" None ">                                                                                    </ListView>        <ImageViewandroid:id= "@+id/empty_view"android:layout_width=" Match_parent "android:layout_height=" Match_parent "android:src=" @mipmap/ic_ Launcher " />                                                    </framelayout>
ListView listView = (ListView) findViewById(R.id.listView);listView.setEmptyView(findViewById(R.id.empty_view));
9.ListView Slide Monitor

There are two main ways to listen for a ListView slide event: One is through Ontouchlistener for listening, the other is to use Onscrolllistener for listening, and usually requires the use of gesturedetector gesture recognition. Velocitytracker sliding speed detection for better monitoring.

9.1 Ontouchlistener

Ontouchlistener is a listener event in view that determines the direction of the user's swipe by listening to the coordinates of the action_down action_move action_up These three events occur. , and the corresponding logic is processed in different events.

Mlistview.setontouchlistener (NewView.ontouchlistener () {@Override             Public Boolean OnTouch(View view, Motionevent motionevent) {Switch(Motionevent.getaction ()) { CaseMotionevent.action_down://Touch-time Operation                         Break; CaseMotionevent.action_move://Mobile Operation                         Break; CaseMOTIONEVENT.ACTION_UP://operation on departure                         Break; }return false; }        });
9.2 Onscrolllistener

Onscrolllistener is a listener event in the Abslistview

Mlistview.setonscrolllistener (NewAbslistview.onscrolllistener () {@Override             Public void onscrollstatechanged(Abslistview Abslistview,intScrollstate) {Switch(scrollstate) { CaseAbsListView.OnScrollListener.SCROLL_STATE_IDLE://Slide StopLOG.D ("Tag","Scroll_state_idle"); Break; CaseAbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL://scrollingLOG.D ("Tag","Scroll_state_touch_scroll"); Break; CaseAbsListView.OnScrollListener.SCROLL_STATE_FLING://Finger toss when the finger is forced to slide after leaving the ListView due to inertia continues to slideLOG.D ("Tag","Scroll_state_fling"); Break; }            }@Override             Public void onscroll(Abslistview Abslistview,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) {//scrolling is always calledLOG.D ("Tag","Onscroll"); }        });

There are two callback methods –onscrollstatechanged () and Onscroll () in Onscrolllistener.
Onscrollstatechanged () determines the number of callbacks based on its parameter scrollstate, Scrollstate has the following three modes:

Onscrolllistener.scroll_state_idle: When scrolling is stopped. Onscrolllistener.scroll_state_touch_scroll: When scrolling is in progress. Onscrolllistener.scroll_state_fling: When the finger is thrown, the finger is forced to slide, after leaving the ListView due to inertia continues to slide the state.

When there is no parabolic state, the callback is 2 times, or the callback is 3 times.
Onscroll () has a callback when the ListView scrolls, and it has 3 parameters that show the scroll state of the current ListView very precisely.

Firstvisibleitem: The ID of the first item currently visible (starting from 0). VisibleItemCount: The total number of item currently visible. Totalitemcount: The total item count for the entire ListView.

The item number that is currently visible, including the item not showing the complete item, which shows Yiche, is also included.

//determine whether to scroll to the last line  Span class= "Hljs-comment" >//the ID of another item currently visible plus the sum of the current visible item equals the total item count, which scrolls to the last row.  if  (Firstvisibleitem + VisibleItemCount = = Totalitemcount && totalitemcount > 0 ) {//scroll to the last line }  
//判断滚动的方向//通过一个成员变量lastVisibleItemPosition来记录上次第一个可视的Item的ID并与当前的可视Item的ID进行比较,即可知道当前滚动的方向if (firstVisibleItem > lastVisibleItemPosition) {                    //上滑     elseif (firstVisibleItem < lastVisibleItemPosition) {                    //下滑    }lastVisibleItemPosition = firstVisibleItem;
//获取可视区域内最后一个Item的idmListView.getLastVisiblePosition();//获取可视区域内第一个Item的idmListVIew.geFirstVisiblePosition();
ListView Example Download link

Not to be continued ...

Android completely conquer the ListView one (utility article)

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.