Simple horizontal ListView implementation (version 1.0), listviewversion
Recently, I am not very busy with my work. I just made a small demo randomly based on my own wishes to implement horizontal ListView. The function is improved with the increase of the version, including left and right scrolling, itemClick, and other basic functions of listView;
Although the demo is super simple, it is a waste of effort to write it. Let's get started.
ListView must need an Adapter object. The core principle of this small demo is to traverse the sub-View in the Adapter cyclically, call the layout method of the sub-view to arrange the sub-View horizontally on the ViewGroup based on the calculated position to form a horizontal view. It's easy, if it doesn't help you, you can see the x on the right side of the page on the browser. If it doesn't, click OK.
Layout (int left, int top, int right, int bottom) is a View method. The four parameters of this method determine the position of childView in parentView, where (left, top) the coordinates of childView in the upper left corner of parentView are determined, while (right, bottom) determines the position of childView in the lower right corner of parentView, as shown in the figure below:
Right and bottom generally need to undergo the following operations: right = left + view. getMeasureWidth (), bottom = top + view. getMeasureHeight (); therefore, it is easy to implement a horizontal ListView. For example:
For example, if the width and height of an item are width and height, the following relationship exists without considering padding:
A. layout (0, 0, width, height ),
B. layout (width, * width, height)
C. layout (2 * width, 0, 3 * width, heigth );
The Code is as follows:
int childLeft = 0;for(int i=0;i<getChildCount();i++) {View child = getChildAt(i);int childWidth = child.getMeasuredWidth();child.layout(childLeft, 0, childWidth+childLeft, child.getMeasuredHeight());childLeft += childWidth+child.getPaddingRight();}
Before layout, use addView to add the View generated by Adapter. getView to the viewGroup. The Code is as follows:
For (int I = 0; I <listAdapter. getCount (); I ++) {View child = listAdapter. getView (I, null, this); // note that before addview, you must perform the measure operation on the view. child = measureChild (child); addView (child );}
So the simple horizontal ListView code can be released:
Public class HListView extends ViewGroup {/** Adapter for storing data **/private ListAdapter listAdapter; public HListView (Context context) {super (context);} public HListView (Context context, attributeSet attrs, int defStyle) {super (context, attrs, defStyle);} public HListView (Context context, AttributeSet attrs) {super (context, attrs);} public ListAdapter getAdapter () {return listAdapter;} public void setAdapter (ListAdapter adapter) {this. listAdapter = adapter;}/*** measure the width and height of each child * @ param view * @ return */private View measureChild (View view) {LayoutParams params = view. getLayoutParams (); if (params = null) {params = new LayoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); view. setLayoutParams (params);} view. measure (MeasureSpec. makeMeasureSpec (getWidth (), MeasureSpec. AT_MOST), MeasureSpec. makeMeasureSpec (getHeight (), MeasureSpec. AT_MOST); return view;} @ Overrideprotected void onLayout (boolean changed, int left, int top, int right, int bottom) {if (listAdapter = null) {return ;} // Add the subview in listView to viewGroup for (int I = 0; I <listAdapter. getCount (); I ++) {View child = listAdapter. getView (I, null, this); child = measureChild (child); addView (child);} // sets the position of the child view in the viewGroup. int childLeft = 0; for (int I = 0; I <getChildCount (); I ++) {View child = getChildAt (I); int childWidth = child. getMeasuredWidth (); child. layout (childLeft, 0, childWidth + childLeft, child. getMeasuredHeight (); childLeft + = childWidth + child. getPaddingRight ();}}}
Run one. Check the effect.
I reported an error when logging into history. The error code is located on addView. The method for tracking the source code addView is as follows:
public void addView(View child) { addView(child, -1); } public void addView(View child, int index) { ...... addView(child, index, params); } public void addView(View child, int index, LayoutParams params) { .... requestLayout(); invalidate(true); addViewInner(child, index, params, false); }private void addViewInner(View child, int index, LayoutParams params, boolean preventRequestLayout) { ....... if (child.getParent() != null) { throw new IllegalStateException("The specified child already has a parent. " + "You must call removeView() on the child's parent first."); } ........ }
Through source code tracing, we can find that addView will call the addViewInner method, and if chid. getParent () is used in this method ()! = Null, an exception is thrown. Why is getParent () not empty? In fact, it is very simple, because we passed this in the third parameter of getView (position, convertView, parentView) of the Adapter. We will find it in the inflate method step by step (For details, refer to this blog post:
// Remember, "root" is null, and "attachToRoot" is "root" in the source code! = Null, so here it is falsepublic View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) {synchronized (mConstructorArgs ){...... view result = root; // The root View, Which is null try {.... final String name = parser. getName (); // node name. if it is a custom View, it is a fully qualified name. // This if statement does not need to be viewed for now if (TAG_MERGE.equals (name )) {// process the <merge/> tag ...} else {// Temp is the root view that was found in the xml // This is the root View corresponding to the xml file, in item. xm L The file contains RelativeLayout View temp = createViewFromTag (name, attrs); ViewGroup. LayoutParams params = null; // The if condition is not true if (root! = Null) {// Create layout params that match root, if supplied // obtain a LayoutParams instance based on the AttributeSet attribute, remember that the caller is root. Params = root. generateLayoutParams (attrs); if (! AttachToRoot) {// reset the LayoutParams of temp // Set the layout params for temp if we are not // attaching. (If we are, we use addView, below) temp. setLayoutParams (params) ;}/// Inflate all children under temp // traverse all child nodes in temp, that is, View rInflate (parser, temp, attrs); // Add the root node of the xml file and the view of the child nodes in the root node to the root node, of course, if the root value is null, It is not executed here if (root! = Null & attachToRoot) {root. addView (temp, params);} // if the root node is null, View if (root = null |! AttachToRoot) {result = temp ;}}... return result ;}}
If (root! = Null) will call root. addView (temp, params) and this root is what we pass this, so when inflate parses the xml file, it will add convertView to parentview by calling addView, so getParent () not null. this is easy to change. You only need to pass the parentView to a null value by getView (position, convetView, parentView.
Maybe some readers will say that removing addView from the HListView method and directly changing it to the following code is not a solution? The modified code is as follows:
For (int I = 0; I <listAdapter. getCount (); I ++) {// call addView child = listAdapter when parsing infate by passing this. getView (I, null, this); child = measureChild (child );}
Run it and try again. The result is that there is nothing on the cell phone screen, only the color set by the backgroud displayed by HlistView:
Is it Mao? If you look at the infate method, you can find that if the value passed by parentView is not null, the View returned by the getView method is parentView, which is printed by listAdapter. getView (I, null, this) = this, you can see that the returned value is true; so we originally wanted childView, and you returned parentView, which indicates that the problem was found, it is very easy to solve this problem, that is, when getView returns, change return convertView to return convertView. findViewById (R. id. item); item is the id of the root node of the xml configuration file
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/item" android:layout_width="100dp" android:layout_height="200dp" >
@Overridepublic View getView(int position, View convertView, ViewGroup parent) {HolderView holderView = null;if(convertView == null ){holderView = new HolderView();convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent);holderView.imageView =(ImageView) convertView.findViewById(R.id.imageView);holderView.textView = (TextView) convertView.findViewById(R.id.textView);convertView.setTag(holderView);}else{holderView = (HolderView) convertView.getTag();}holderView.imageView.setImageResource((Integer) mList.get(position).get("img"));holderView.textView.setText((String) mList.get(position).get("index"));return convertView.findViewById(R.id.item);}
The final running effect is as follows:
Simple horizontal listVIew version1.0 came out. But now I try the most simple function to see that some images on the page are not completely displayed, and cannot be rolled, and there is no response for clicking. As for the improvement of functions, version2.0 will gradually improve. Here is the source code download link
Project source code