如何用章节标题xamarin android创建一个Android ListView?我有17个错误

时间:2016-04-18 04:09:39

标签: android xamarin xamarin.android

在此示例中,我们将展示如何使用节头创建ListView。这涉及以下步骤

为List标题和List行创建两个自定义布局 为ListView创建自定义适配器 在您的活动中实例化ListView

我有17个错误。我想用章节标题xamarin android创建listview。 http://javatechig.com/android/listview-with-section-header-in-android

我从java转换为C#

>  - `public class CustomAdapter:BaseAdapter`->does not implement abstract member `android.widget.baseAdapter.getitem(int)`
>  - `Android.Widget.BaseAdapter.NotifyDataSetChanged ()`-> An object reference is requered to access non-static member .....
>  - `return mData.GetRange(position)`;-> no overload for method 'getrange'take 1 arguments
>  - `convertView = mInflater.Inflate(Resource.Layout.textViewHeaderItems, false)`;-> the
> best overloaded method match for ..... has some invalid arguments
>  - `convertView.SetTag(holder);`-> no overload for method ... tkae 2 arguments
>  - `holder.textView.SetText(mData.get(position))`; type system.collection.generic.list<string> does not contain a defintion
> for 'get'and no extension method 'get'of type
> `system.Colleciton.Generic.List<string>` could be found. Are you
> missing an assembly

public class CustomAdapter:BaseAdapter
		{
			private  const int TYPE_ITEM = 0;
			private  const int TYPE_SEPARATOR = 1;

			private List<String> mData = new List<String>();
			private TreeSet sectionHeader = new TreeSet();

			private LayoutInflater mInflater;

			public CustomAdapter(Context context) {
				mInflater = (LayoutInflater) context
					.GetSystemService(Context.LayoutInflaterService);
			}

			public void addItem(String item) {
				mData.Add(item);
				Android.Widget.BaseAdapter.NotifyDataSetChanged ();
			}

			public void addSectionHeaderItem(String item) {
				mData.Add(item);
				sectionHeader.Add(mData.Count - 1);
				Android.Widget.BaseAdapter.NotifyDataSetChanged ();
			}

		
			public int getItemViewType(int position) {
				return sectionHeader.Contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
			}

	
			public int getViewTypeCount() {
				return 2;
			}

	
			public int getCount() {
				return mData.Count;
			}

		
			public String getItem(int position) {
				return mData.GetRange(position);
			}

		
			public long getItemId(int position) {
				return position;
			}

			public View getView(int position, View convertView, ViewGroup parent) {
				ViewHolder holder = null;
				int rowType = getItemViewType(position);

				if (convertView == null) {
					holder = new ViewHolder();
					switch (rowType) {
					case TYPE_ITEM:
						convertView = mInflater.Inflate(Resource.Layout.textViewHeaderItems, false);
						holder.textView = (TextView) convertView.FindViewById(Resource.Id.textviewHeaderItems);
						break;
					case TYPE_SEPARATOR:
						convertView = mInflater.Inflate(Resource.Layout.textViewItemsSeparator, false);
						holder.textView = (TextView) convertView.FindViewById(Resource.Id.textviewItemsSeparator);
						break;
					}
					convertView.SetTag(holder);
				} else {
					holder = (ViewHolder) convertView.GetTag();
				}
				holder.textView.SetText(mData.get(position));

				return convertView;
			}

			public class ViewHolder {
				public TextView textView;
			}
		}

2 个答案:

答案 0 :(得分:1)

您应该使用&#34;搜索&#34;在Xamarin的Dev网站上发挥以下问题的作用:

注意:对于像这样的问题,Google或Bing也是您最好的朋友。

Android.Content.Context.LayoutInflaterService

  

与Context.GetSystemService(String)一起使用,以检索LayoutInflater,以便在此上下文中展开布局资源。

https://developer.xamarin.com/api/field/Android.Content.Context.LayoutInflaterService/

Android.Widget.BaseAdapter.NotifyDataSetChanged

  

通知附加的观察者基础数据已被更改,反映数据集的任何视图都应自行刷新。

https://developer.xamarin.com/api/member/Android.Widget.BaseAdapter.NotifyDataSetChanged/

Java.Util.TreeSet

  

TreeSet是SortedSet的一个实现。

https://developer.xamarin.com/api/type/Java.Util.TreeSet/

答案 1 :(得分:0)

我遇到了一个问题,我最终还是根据this blog post创建了一个ListView部分标题。这就是我做的方式,以防有人遇到同样的问题:

定义标题和将在ListView内填充的列表项的布局:

<强> adapter_expandable_listview_header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/adapter_expandable_listview_header_textview"
        android:layout_width="match_parent"
        android:text="Header"
        android:textStyle="bold"
        android:textSize="14sp"
        android:textColor="@color/textColorSecondary"
        android:layout_height="wrap_content"
        android:layout_margin="16dp" />
</LinearLayout>

<强> adapter_expandable_listview_listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minWidth="25px"
    android:minHeight="25px">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/relativeLayout1"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="20dp"
        android:descendantFocusability="blocksDescendants">
        <TextView
            android:text="Rüttenscheider Stern"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/adapter_expandable_listview_listitem_textview1"
            android:textSize="16sp"
            android:textColor="@color/textColorPrimary" />
        <TextView
            android:text="Essen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/adapter_expandable_listview_listitem_textview1"
            android:id="@+id/adapter_expandable_listview_listitem_textview2"
            android:textSize="14sp" />
        <TextView
            android:text="Rüttenscheiderstraße"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/adapter_expandable_listview_listitem_textview2"
            android:id="@+id/adapter_expandable_listview_listitem_textview3"
            android:textSize="14sp" />
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:id="@+id/adapter_expandable_listview_listitem_overflow_button"
            android:src="@drawable/ic_dots_vertical_grey600_18dp"
            android:background="@null" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_marginLeft="16dp"
        android:layout_height="1dp"
        android:background="@color/material_grey_300" />
</LinearLayout>

这是ListView的适配器:

<强> SectionedHeaderListViewAdaper.cs

namespace YourNamespace
{
    /// <summary>
    /// Used to pass groups of objects to the adapter.
    /// </summary>
    internal class ExpandableItem
    {
        public string HeaderTitle;
        public List<FMNavigationListItem> ChildItems;
    }

    /// <summary>
    /// Used internally by the adapter.
    /// </summary>
    internal class SectionedHeaderListItem
    {
        public string HeaderTitle;
        public FMNavigationListItem Item;

        public SectionedHeaderListItem(string headerTitle, FMNavigationListItem item)
        {
            HeaderTitle = headerTitle;
            Item = item;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    class SectionedHeaderListViewAdaper : BaseAdapter
    {
        const int TypeItem = 0;
        const int TypeSeperator = 1;

        LayoutInflater mLayoutInflater;
        List<SectionedHeaderListItem> mDataItems;
        List<int> mSectionPositions;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="items"></param>
        public SectionedHeaderListViewAdaper(Context context, List<ExpandableItem> items)
        {
            mLayoutInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
            mSectionPositions = new List<int>();

            // Sort each item via header title.
            List<ExpandableItem> dataItems = items;
            dataItems.Sort(delegate (ExpandableItem e1, ExpandableItem e2)
            {
                return e1.HeaderTitle.CompareTo(e2.HeaderTitle);
            });

            // Sort each child item alphabetically.
            foreach (var d in dataItems)
            {
                d.ChildItems.Sort(delegate (FMNavigationListItem i1, FMNavigationListItem i2)
                {
                    return i1.DisplayAttributes[0].CompareTo(i2.DisplayAttributes[0]);
                });
            }

            // Merge all items into one big list.
            mDataItems = new List<SectionedHeaderListItem>();
            int index = 0;
            foreach (var expandableItem in dataItems)
            {
                // Represents a section
                mDataItems.Add(new SectionedHeaderListItem(
                    expandableItem.HeaderTitle,
                    null));
                mSectionPositions.Add(index);
                index++;

                // Now add the child items for the section
                foreach (var dataItem in expandableItem.ChildItems)
                {
                    mDataItems.Add(new SectionedHeaderListItem(
                       expandableItem.HeaderTitle,
                       dataItem));
                    index++;
                }
            }
        }

        public override Java.Lang.Object GetItem(int position)
        {
            return position;
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        public FMNavigationListItem ItemAt(int position)
        {
            return mDataItems[position].Item;
        }

        /// <summary>
        /// One view for the header and another for
        /// the normal cells.
        /// </summary>
        public override int ViewTypeCount
        {
            get
            {
                return 2;
            }
        }

        public override int GetItemViewType(int position)
        {
            if (mSectionPositions.Contains(position))
                return TypeSeperator;
            return TypeItem;
        }

        public override int Count
        {
            get
            {
                return mDataItems.Count;
            }
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            SectionedHeaderListViewAdaperViewHolder holder = null;
            int rowType = GetItemViewType(position);

            // Inflate the correct layout
            if (convertView == null)
            {
                holder = new SectionedHeaderListViewAdaperViewHolder();
                switch(rowType)
                {
                    case TypeItem:
                        convertView = mLayoutInflater.Inflate(
                            Resource.Layout.adapter_expandable_listview_listitem, 
                            null);
                       break;
                    case TypeSeperator:
                        convertView = mLayoutInflater.Inflate(
                            Resource.Layout.adapter_expandable_listview_header,
                            null);
                        break;
                }
                convertView.Tag = (SectionedHeaderListViewAdaperViewHolder)convertView.Tag;
            }
            else
            {
                holder = (SectionedHeaderListViewAdaperViewHolder)convertView.Tag;
            }

            //Populate UI components
            SectionedHeaderListItem item = mDataItems[position];
            switch (rowType)
            {
                case TypeItem:
                    // Horrible code incomming
                    holder.DispAttsTextViews = new List<TextView>();
                    holder.DispAttsTextViews.Add(convertView.FindViewById<TextView>(Resource.Id.adapter_expandable_listview_listitem_textview1));
                    holder.DispAttsTextViews.Add(convertView.FindViewById<TextView>(Resource.Id.adapter_expandable_listview_listitem_textview2));
                    holder.DispAttsTextViews.Add(convertView.FindViewById<TextView>(Resource.Id.adapter_expandable_listview_listitem_textview3));
                    holder.DispAttsTextViews[0].Text = item.Item.DisplayAttributes[0];
                    holder.DispAttsTextViews[1].Text = item.Item.DisplayAttributes[1];
                    holder.DispAttsTextViews[2].Text = item.Item.DisplayAttributes[2];
                    break;
                case TypeSeperator:
                    holder.HeaderTextView = convertView.FindViewById<TextView>(Resource.Id.adapter_expandable_listview_header_textview);
                    holder.HeaderTextView.Text = item.HeaderTitle;
                    break;
            }
            return convertView;
        }
    }

    class SectionedHeaderListViewAdaperViewHolder : Java.Lang.Object
    {
        public TextView HeaderTextView { get; set; }
        public List<TextView> DispAttsTextViews { get; set; }
    }

您可以更改FMNavigationListItem对象,因为我在内部使用的是我的数据项。其背后的想法是将数据分组到ExpandableItem个对象中,每个对象都有一个标题标题。适配器获取这些对象并将它们合并到一个大列表中。

您可以查看结果here