Skip to content Skip to sidebar Skip to footer

How To Add Section Header In Listview List Item

I want to Develop 'History of Country' Android Application. But I have a problem. I can not put Country Header in Listview List Item. I want to put Header; Such as 'Africa : North

Solution 1:

Screen Shot

enter image description here

activity_main.xml

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><EditTextandroid:id="@+id/edtSearch"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_vertical"android:hint="Search..."android:padding="10dp" /><ListViewandroid:id="@+id/lvCountry"android:layout_width="match_parent"android:layout_height="match_parent" ></ListView></LinearLayout>

layout_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/tvItemTitle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="10dp"android:text="Item" /></LinearLayout>

layout_section.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#D8D8D8"android:orientation="vertical" ><TextViewandroid:id="@+id/tvSectionTitle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:padding="10dp"android:text="Section"android:textStyle="bold" /></LinearLayout>

MainActivity.java

publicclassMainActivityextendsActionBarActivity {

    private ListView lvCountry;
    private EditText edtSearch;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtSearch = (EditText) findViewById(R.id.edtSearch);
        lvCountry = (ListView) findViewById(R.id.lvCountry);

        ArrayList<Item> countryList = newArrayList<MainActivity.Item>();
        // Header
        countryList.add(newSectionItem("Asia"));
        // State Name
        countryList.add(newEntryItem("India"));
        countryList.add(newEntryItem("China"));
        countryList.add(newEntryItem("Hong Kong"));
        countryList.add(newEntryItem("Nepal"));

        // Header
        countryList.add(newSectionItem("North Asia"));
        // State Name
        countryList.add(newEntryItem("Belarus"));
        countryList.add(newEntryItem("Moldova"));
        countryList.add(newEntryItem("Russian Federation"));
        countryList.add(newEntryItem("Ukraine"));

        // Header
        countryList.add(newSectionItem("North America"));
        // State Name
        countryList.add(newEntryItem("Canada"));
        countryList.add(newEntryItem("Saint Pierre and Miquelon"));
        countryList.add(newEntryItem("United States"));

        // Header
        countryList.add(newSectionItem("North & Central America"));
        // State Name
        countryList.add(newEntryItem("Caribbean Islands"));
        countryList.add(newEntryItem("Anguilla"));
        countryList.add(newEntryItem("Antigua and Barbuda"));
        countryList.add(newEntryItem("Aruba"));

        // set adapterfinalCountryAdapteradapter=newCountryAdapter(this, countryList);
        lvCountry.setAdapter(adapter);
        lvCountry.setTextFilterEnabled(true);

        // filter on text change
        edtSearch.addTextChangedListener(newTextWatcher() {

            @OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
                if(adapter != null)
                {
                    adapter.getFilter().filter(s.toString());
                }
            }

            @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @OverridepublicvoidafterTextChanged(Editable s) {
            }
        });
    }

    /**
     * row item
     */publicinterfaceItem {
        publicbooleanisSection();
        public String getTitle();
    }

    /**
     * Section Item
     */publicclassSectionItemimplementsItem {
        privatefinal String title;

        publicSectionItem(String title) {
            this.title = title;
        }

        public String getTitle() {
            return title;
        }

        @OverridepublicbooleanisSection() {
            returntrue;
        }
    }

    /**
     * Entry Item
     */publicclassEntryItemimplementsItem {
        publicfinal String title;

        publicEntryItem(String title) {
            this.title = title;
        }

        public String getTitle() {
            return title;
        }

        @OverridepublicbooleanisSection() {
            returnfalse;
        }
    }

    /**
     * Adapter
     */publicclassCountryAdapterextendsBaseAdapter {
        private Context context;
        private ArrayList<Item> item;
        private ArrayList<Item> originalItem;

        publicCountryAdapter() {
            super();
        }

        publicCountryAdapter(Context context, ArrayList<Item> item) {
            this.context = context;
            this.item = item;
            //this.originalItem = item;
        }

        @OverridepublicintgetCount() {
            return item.size();
        }

        @Overridepublic Object getItem(int position) {
            return item.get(position);
        }

        @OverridepubliclonggetItemId(int position) {
            return position;
        }

        @Overridepublic View getView(int position, View convertView, ViewGroup parent)
        {
            LayoutInflaterinflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (item.get(position).isSection()) {
                // if section header
                convertView = inflater.inflate(R.layout.layout_section, parent, false);
                TextViewtvSectionTitle= (TextView) convertView.findViewById(R.id.tvSectionTitle);
                tvSectionTitle.setText(((SectionItem) item.get(position)).getTitle());
            }
            else
            {
                // if item
                convertView = inflater.inflate(R.layout.layout_item, parent, false);
                TextViewtvItemTitle= (TextView) convertView.findViewById(R.id.tvItemTitle);
                tvItemTitle.setText(((EntryItem) item.get(position)).getTitle());
            }

            return convertView;
        }

        /**
         * Filter
         */public Filter getFilter()
        {
            Filterfilter=newFilter() {

                @SuppressWarnings("unchecked")@OverrideprotectedvoidpublishResults(CharSequence constraint, FilterResults results) {

                    item = (ArrayList<Item>) results.values;
                    notifyDataSetChanged();
                }

                @SuppressWarnings("null")@Overrideprotected FilterResults performFiltering(CharSequence constraint) {

                    FilterResultsresults=newFilterResults();
                    ArrayList<Item> filteredArrayList = newArrayList<Item>();


                    if(originalItem == null || originalItem.size() == 0)
                    {
                        originalItem = newArrayList<Item>(item);
                    }

                    /*
                     * if constraint is null then return original value
                     * else return filtered value
                     */if(constraint == null && constraint.length() == 0)
                    {
                        results.count = originalItem.size();
                        results.values = originalItem;
                    }
                    else
                    {
                        constraint = constraint.toString().toLowerCase(Locale.ENGLISH);
                        for (inti=0; i < originalItem.size(); i++) 
                        {
                            Stringtitle= originalItem.get(i).getTitle().toLowerCase(Locale.ENGLISH);
                            if(title.startsWith(constraint.toString()))
                            {
                                filteredArrayList.add(originalItem.get(i));
                            }
                        }
                        results.count = filteredArrayList.size();
                        results.values = filteredArrayList;
                    }

                    return results;
                }
            };

            return filter;
        }
    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.sectionheader"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="11"android:targetSdkVersion="21" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"android:windowSoftInputMode="stateHidden|adjustPan"android:label="@string/app_name" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

Post a Comment for "How To Add Section Header In Listview List Item"