New list with sticky list headers library

This commit is contained in:
Dominik Schürmann 2014-01-02 21:10:08 +01:00
parent 1d91804dc7
commit f5da63f988
63 changed files with 3687 additions and 61 deletions

View File

@ -88,8 +88,7 @@
android:name=".ui.KeyListPublicActivity"
android:configChanges="orientation|screenSize|keyboardHidden|keyboard"
android:label="@string/title_manage_public_keys"
android:launchMode="singleTop"
android:uiOptions="splitActionBarWhenNarrow" >
android:launchMode="singleTop" >
<!-- <intent-filter> -->
<!-- <action android:name="android.intent.action.SEARCH" /> -->
@ -104,8 +103,7 @@
android:name=".ui.KeyListSecretActivity"
android:configChanges="orientation|screenSize|keyboardHidden|keyboard"
android:label="@string/title_manage_secret_keys"
android:launchMode="singleTop"
android:uiOptions="splitActionBarWhenNarrow" >
android:launchMode="singleTop" >
<!-- <intent-filter> -->
<!-- <action android:name="android.intent.action.SEARCH" /> -->

View File

@ -4,6 +4,7 @@ buildscript {
}
dependencies {
// NOTE: Avoid using dynamic versions (+). This breaks offline builds!
classpath 'com.android.tools.build:gradle:0.6.3'
}
}
@ -22,7 +23,7 @@ dependencies {
compile 'com.android.support:support-v4:18.0.+' // already in actionbarsherlock
compile project(':libraries:ActionBarSherlock')
compile project(':libraries:HtmlTextView')
compile project(':libraries:pinned-section-listview:library')
compile project(':libraries:StickyListHeaders:library')
}
android {

View File

@ -11,3 +11,4 @@
target=android-19
android.library.reference.1=../libraries/ActionBarSherlock
android.library.reference.2=../libraries/HtmlTextView
android.library.reference.3=../libraries/StickyListHeaders/library

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@color/header_pressed" />
<item android:drawable="@color/header_normal" />
</selector>

View File

@ -8,18 +8,7 @@
android:id="@+id/key_list_public_fragment"
android:name="org.sufficientlysecure.keychain.ui.KeyListPublicFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_weight="1"
android:background="@drawable/abs__ab_bottom_solid_light_holo"
android:paddingBottom="3dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="3dp"
android:text="@string/list_information" />
</LinearLayout>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<se.emilsjolander.stickylistheaders.StickyListHeadersListView
android:id="@+id/key_list_public_fragment_stickylist"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

View File

@ -8,18 +8,7 @@
android:id="@+id/key_list_secret_fragment"
android:name="org.sufficientlysecure.keychain.ui.KeyListSecretFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_weight="1"
android:background="@drawable/abs__ab_bottom_solid_light_holo"
android:paddingBottom="3dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="3dp"
android:text="@string/list_information" />
</LinearLayout>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/header_selector" >
<se.emilsjolander.stickylistheaders.views.UnderlineTextView
android:id="@+id/stickylist_header_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|left"
android:padding="5dp"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>

View File

@ -3,5 +3,8 @@
<color name="emphasis">#31b6e7</color>
<color name="bg_gray">#cecbce</color>
<color name="header_normal">#ffe74c3c</color>
<color name="header_pressed">#ffc0392b</color>
<color name="menu_section_header">#FFDDDDDD</color>
</resources>

View File

@ -210,7 +210,6 @@
<string name="lookup_unknown_key">Unknown key %s, do you want to try finding it on a keyserver?</string>
<string name="key_send_success">Successfully sent key to server</string>
<string name="key_sign_success">Successfully signed key</string>
<string name="list_information">Long press one entry in this list to show more options!</string>
<string name="list_empty">This list is empty!</string>
<string name="nfc_successfull">Successfully sent key with NFC Beam!</string>

View File

@ -24,6 +24,9 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds;
import org.sufficientlysecure.keychain.ui.adapter.KeyListPublicAdapter;
import se.emilsjolander.stickylistheaders.ApiLevelTooLowException;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
@ -31,58 +34,84 @@ import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.app.SherlockFragment;
public class KeyListPublicFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
/**
* Public key list with sticky list headers.
*
* - uses StickyListHeaders library
* - custom adapter: KeyListPublicAdapter
*
* TODO:
* - fix loader with spinning animation
* - fix design
* - fix view holder in adapter
*
*/
public class KeyListPublicFragment extends SherlockFragment implements
AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private KeyListPublicActivity mKeyListPublicActivity;
private KeyListPublicAdapter mAdapter;
StickyListHeadersListView stickyList;
/**
* Define Adapter and Loader on create of Activity
*/
@SuppressLint("NewApi")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mKeyListPublicActivity = (KeyListPublicActivity) getActivity();
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// start key view on click
Intent detailsIntent = new Intent(mKeyListPublicActivity, KeyViewActivity.class);
detailsIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsUri(Long
.toString(id)));
startActivity(detailsIntent);
}
});
stickyList = (StickyListHeadersListView) getActivity().findViewById(
R.id.key_list_public_fragment_stickylist);
stickyList.setOnItemClickListener(this);
// stickyList.setOnHeaderClickListener(this);
// stickyList.setOnStickyHeaderOffsetChangedListener(this);
// mStickyList.addHeaderView(inflater.inflate(R.layout.list_header, null));
// mStickyList.addFooterView(inflater.inflate(R.layout.list_footer, null));
// stickyList.setEmptyView(findViewById(R.id.empty));
stickyList.setAreHeadersSticky(true);
stickyList.setDrawingListUnderStickyHeader(true);
stickyList.setFastScrollEnabled(true);
try {
stickyList.setFastScrollAlwaysVisible(true);
} catch (ApiLevelTooLowException e) {
}
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText(getString(R.string.list_empty));
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// setEmptyText(getString(R.string.list_empty));
// Start out with a progress indicator.
setListShown(false);
// setListShown(false);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new KeyListPublicAdapter(mKeyListPublicActivity, null, Id.type.public_key);
setListAdapter(mAdapter);
// mAdapter = new KeyListPublicAdapter(mKeyListPublicActivity, null, Id.type.public_key);
// setListAdapter(mAdapter);
// stickyList.setAdapter(mAdapter);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.key_list_public_fragment, container, false);
return view;
}
// These are the rows that we will retrieve.
static final String[] PROJECTION = new String[] { KeyRings._ID, KeyRings.MASTER_KEY_ID,
UserIds.USER_ID };
@ -104,13 +133,19 @@ public class KeyListPublicFragment extends SherlockListFragment implements
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
// mAdapter.swapCursor(data);
int userIdIndex = data.getColumnIndex(UserIds.USER_ID);
mAdapter = new KeyListPublicAdapter(mKeyListPublicActivity, data, Id.type.public_key,
userIdIndex);
stickyList.setAdapter(mAdapter);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
// setListShown(true);
} else {
setListShownNoAnimation(true);
// setListShownNoAnimation(true);
}
}
@ -122,4 +157,12 @@ public class KeyListPublicFragment extends SherlockListFragment implements
mAdapter.swapCursor(null);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// start key view on click
Intent detailsIntent = new Intent(mKeyListPublicActivity, KeyViewActivity.class);
detailsIntent.setData(KeychainContract.KeyRings.buildPublicKeyRingsUri(Long.toString(id)));
startActivity(detailsIntent);
}
}

View File

@ -17,30 +17,40 @@
package org.sufficientlysecure.keychain.ui.adapter;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.OtherHelper;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds;
import org.sufficientlysecure.keychain.util.SectionCursorAdapter;
import org.sufficientlysecure.keychain.util.Log;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class KeyListPublicAdapter extends SectionCursorAdapter {
/**
* - implements StickyListHeadersAdapter from library - uses view holder pattern for performance
*
*/
public class KeyListPublicAdapter extends CursorAdapter implements StickyListHeadersAdapter {
private LayoutInflater mInflater;
public KeyListPublicAdapter(Context context, Cursor c, int flags) {
super(context, c, android.R.layout.preference_category, 2); // TODO: 2 is user id
int mSectionColumnIndex;
public KeyListPublicAdapter(Context context, Cursor c, int flags, int sectionColumnIndex) {
super(context, c, flags);
mInflater = LayoutInflater.from(context);
mSectionColumnIndex = sectionColumnIndex;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO: view holder pattern?
int userIdIndex = cursor.getColumnIndex(UserIds.USER_ID);
TextView mainUserId = (TextView) view.findViewById(R.id.mainUserId);
@ -74,4 +84,64 @@ public class KeyListPublicAdapter extends SectionCursorAdapter {
return mInflater.inflate(R.layout.key_list_group_item, null);
}
@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
if (convertView == null) {
holder = new HeaderViewHolder();
convertView = mInflater.inflate(R.layout.stickylist_header, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.stickylist_header_text);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
if (!mDataValid) {
// no data available at this point
Log.d(Constants.TAG, "getHeaderView: No data available at this point!");
return convertView;
}
// similar to getView in CursorAdapter
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
// set header text as first char in name
String headerText = "" + mCursor.getString(mSectionColumnIndex).subSequence(0, 1).charAt(0);
holder.text.setText(headerText);
return convertView;
}
/**
* Remember that these have to be static, position=1 should always return the same Id that is.
*/
@Override
public long getHeaderId(int position) {
if (!mDataValid) {
// no data available at this point
Log.d(Constants.TAG, "getHeaderView: No data available at this point!");
return -1;
}
// similar to getView in CursorAdapter
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
// return the first character of the name as ID because this is what
// headers are based upon
return mCursor.getString(mSectionColumnIndex).subSequence(0, 1).charAt(0);
}
class HeaderViewHolder {
TextView text;
}
class ViewHolder {
TextView mainUserId;
TextView mainUserIdRest;
}
}

View File

@ -0,0 +1,50 @@
package se.emilsjolander.stickylistheaders.views;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* @author Eric Frohnhoefer
*/
public class UnderlineTextView extends TextView {
private final Paint mPaint = new Paint();
private int mUnderlineHeight = 0;
public UnderlineTextView(Context context) {
this(context, null);
}
public UnderlineTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public UnderlineTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
Resources r = getResources();
mUnderlineHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, r.getDisplayMetrics());
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom + mUnderlineHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the underline the same color as the text
mPaint.setColor(getTextColors().getDefaultColor());
canvas.drawRect(0, getHeight() - mUnderlineHeight, getWidth(), getHeight(), mPaint);
}
}

98
libraries/StickyListHeaders/.gitignore vendored Normal file
View File

@ -0,0 +1,98 @@
###Android###
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
# Eclipse project files
.classpath
.project
###Eclipse###
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
###Maven###
target/
###Gradle###
.gradle/
build/
###IntelliJ###
*.iml
*.ipr
*.iws
.idea/
###Actionscript###
# Build and Release Folders
bin/
bin-debug/
bin-release/
# Project property files
.actionScriptProperties
.flexProperties
.settings/
.project
###OSX###
.DS_Store
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes

View File

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,203 @@
StickyListHeaders
=================
StickyListHeaders is an Android library that makes it easy to integrate section headers in your `ListView`. These section headers stick to the top like in the new People app of Android 4.0 Ice Cream Sandwich. This behavior is also found in lists with sections on iOS devices. This library can also be used without the sticky functionality if you just want section headers.
StickyListHeaders actively supports android versions 2.3 (gingerbread) and above.
That said, it works all the way down to 2.1 but is not actively tested or working perfectly.
Here is a short gif showing the functionality you get with this library:
![alt text](https://github.com/emilsjolander/StickyListHeaders/raw/master/demo.gif "Demo gif")
Goal
----
The goal of this project is to deliver a high performance replacement to `ListView`. You should with minimal effort and time be able to add section headers to a list. This should be done via a simple to use API without any special features. This library will always priorities general use cases over special ones. This means that the library will add very few public methods to the standard `ListView` and will not try to work for every use case. While I will want to support even narrow use cases I will not do so if it compromises the API or any other feature.
Installing
---------------
###Gradle
Add the following gradle dependency exchanging `x.x.x` for the latest release.
```groovy
dependencies {
compile 'se.emilsjolander:stickylistheaders:x.x.x'
}
```
###Cloning
First of all you will have to clone the library.
```shell
git clone https://github.com/emilsjolander/StickyListHeaders.git
```
Now that you have the library you will have to import it into Android Studio.
In Android Studio navigate the menus like this.
```
File -> Import Project ...
```
In the following dialog navigate to StickyListHeaders which you cloned to your computer in the previous steps and select the `build.gradle`.
Getting Started
---------------
Ok lets start with your activities or fragments xml file. It might look something like this.
```xml
<se.emilsjolander.stickylistheaders.StickyListHeadersListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
Now in your activities `onCreate()` or your fragments `onCreateView()` you would want to do something like this
```java
StickyListHeadersListView stickyList = (StickyListHeadersListView) findViewById(R.id.list);
MyAdapter adapter = new MyAdapter(this);
stickyList.setAdapter(adapter);
```
`MyAdapter` in the above example would look something like this if your list was a list of countries where each header was for a letter in the alphabet.
```java
public class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter {
private String[] countries;
private LayoutInflater inflater;
public TestBaseAdapter(Context context) {
inflater = LayoutInflater.from(context);
countries = context.getResources().getStringArray(R.array.countries);
}
@Override
public int getCount() {
return countries.length;
}
@Override
public Object getItem(int position) {
return countries[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.test_list_item_layout, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(countries[position]);
return convertView;
}
@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
if (convertView == null) {
holder = new HeaderViewHolder();
convertView = inflater.inflate(R.layout.header, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
//set header text as first char in name
String headerText = "" + countries[position].subSequence(0, 1).charAt(0);
holder.text.setText(headerText);
return convertView;
}
@Override
public long getHeaderId(int position) {
//return the first character of the country as ID because this is what headers are based upon
return countries[position].subSequence(0, 1).charAt(0);
}
class HeaderViewHolder {
TextView text;
}
class ViewHolder {
TextView text;
}
}
```
That's it! Look through the API docs below to get know about things to customize and if you have any problems getting started please open an issue as it probably means the getting started guide need some improvement!
Upgrading from 1.x versions
---------------------------
First of all the package name has changed from `com.emilsjolander.components.stickylistheaders` -> `se.emilsjolander.stickylistheaders` so update all your imports and xml files using StickyListHeaders!
If you are Upgrading from a version prior to 2.x you might run into the following problems.
1. `StickyListHeadersListView` is no longer a `ListView` subclass. This means that it cannot be passed into a method expecting a ListView. You can retrieve an instance of the `ListView` via `getWrappedList()` but use this with caution as things will probably break if you start setting things directly on that list.
2. Because `StickyListHeadersListView` is no longer a `ListView` it does not support all the methods. I have implemented delegate methods for all the usual methods and gladly accept pull requests for more.
API
---
###StickyListHeadersAdapter
```java
public interface StickyListHeadersAdapter extends ListAdapter {
View getHeaderView(int position, View convertView, ViewGroup parent);
long getHeaderId(int position);
}
```
Your adapter must implement this interface to function with `StickyListHeadersListView`.
`getHeaderId()` must return a unique integer for every section. A valid implementation for a list with alphabetical sections is the return the char value of the section that `position` is a part of.
`getHeaderView()` works exactly like `getView()` in a regular `ListAdapter`.
###StickyListHeadersListView
Headers are sticky by default but that can easily be changed with this setter. There is of course also a matching getter for the sticky property.
```java
public void setAreHeadersSticky(boolean areHeadersSticky);
public boolean areHeadersSticky();
```
A `OnHeaderClickListener` is the header version of OnItemClickListener. This is the setter for it and the interface of the listener. The currentlySticky boolean flag indicated if the header that was clicked was sticking to the top at the time it was clicked.
```java
public void setOnHeaderClickListener(OnHeaderClickListener listener);
public interface OnHeaderClickListener {
public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId, boolean currentlySticky);
}
```
A `OnStickyHeaderOffsetChangedListener` is a Listener used for listening to when the sticky header slides out of the screen. The offset parameter will slowly grow to be the same size as the headers height. Use the listeners callback to transform the header in any way you see fit, the standard android contacts app dims the text for example.
```java
public void setOnStickyHeaderOffsetChangedListener(OnStickyHeaderOffsetChangedListener listener);
public interface OnStickyHeaderOffsetChangedListener {
public void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset);
}
```
Here are two methods added to the API for inspecting the children of the underlying `ListView`. I could not override the normal `getChildAt()` and `getChildCount()` methods as that would mess up the underlying measurement system of the `FrameLayout` wrapping the `ListView`.
```java
public View getListChildAt(int index);
public int getListChildCount();
```
This is a setter and getter for an internal attribute that controls if the list should be drawn under the stuck header. The default value is true. If you do not want to see the list scroll under your header you will want to set this attribute to `false`.
```java
public void setDrawingListUnderStickyHeader(boolean drawingListUnderStickyHeader);
public boolean isDrawingListUnderStickyHeader();
```
Contributing
------------
Contributions are very welcome. Now that this library has grown in popularity i have a hard time keeping upp with all the issues while tending to a multitude of other projects as well as school. So if you find a bug in the library or want a feature and think you can fix it yourself, fork + pull request and i will greatly appreciate it!
I love getting pull requests for new features as well as bugs. However, when it comes to new features please also explain the use case and way you think the library should include it. If you don't want to start coding a feature without knowing if the feature will have chance of being included, open an issue and we can discuss the feature!

View File

@ -0,0 +1,24 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
def isReleaseBuild() {
return version.contains("SNAPSHOT") == false
}
allprojects {
version = VERSION_NAME
group = GROUP
repositories {
mavenCentral()
}
}
apply plugin: 'android-reporting'

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Tue Nov 19 08:36:06 CET 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip

164
libraries/StickyListHeaders/gradlew vendored Normal file
View File

@ -0,0 +1,164 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
libraries/StickyListHeaders/gradlew.bat vendored Normal file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,2 @@
.gradle
build

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="se.emilsjolander.stickylistheaders"
android:versionCode="2"
android:versionName="2.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="18" />
</manifest>

View File

@ -0,0 +1,16 @@
apply plugin: 'android-library'
android {
compileSdkVersion 19
buildToolsVersion '19.0.0'
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
}
}
apply from: 'https://raw.github.com/chrisbanes/gradle-mvn-push/eaa6b5404b7594e6c23b884fdc5795f545db55dd/gradle-mvn-push.gradle'

View File

@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="library" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- if sdk.dir was not set from one of the property file, then
get it from the ANDROID_HOME env var.
This must be done before we load project.properties since
the proguard config can use sdk.dir -->
<property environment="env" />
<condition property="sdk.dir" value="${env.ANDROID_HOME}">
<isset property="env.ANDROID_HOME" />
</condition>
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

View File

@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -0,0 +1,15 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19
android.library=true

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="StickyListHeadersListView">
<!-- View attributes -->
<attr name="android:clipToPadding" />
<attr name="android:padding" />
<attr name="android:paddingLeft" />
<attr name="android:paddingTop" />
<attr name="android:paddingRight" />
<attr name="android:paddingBottom" />
<!-- ListView attributes -->
<attr name="android:fadingEdgeLength" />
<attr name="android:requiresFadingEdge" />
<attr name="android:cacheColorHint" />
<attr name="android:choiceMode" />
<attr name="android:drawSelectorOnTop" />
<attr name="android:fastScrollEnabled" />
<attr name="android:fastScrollAlwaysVisible" />
<attr name="android:listSelector" />
<attr name="android:scrollingCache" />
<attr name="android:scrollbarStyle" />
<attr name="android:divider" />
<attr name="android:dividerHeight" />
<!-- StickyListHeaders attributes -->
<attr name="hasStickyHeaders" format="boolean" />
<attr name="isDrawingListUnderStickyHeader" format="boolean" />
</declare-styleable>
</resources>

View File

@ -0,0 +1,225 @@
package se.emilsjolander.stickylistheaders;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.ListAdapter;
/**
* A {@link ListAdapter} which wraps a {@link StickyListHeadersAdapter} and
* automatically handles wrapping the result of
* {@link StickyListHeadersAdapter#getView(int, android.view.View, android.view.ViewGroup)}
* and
* {@link StickyListHeadersAdapter#getHeaderView(int, android.view.View, android.view.ViewGroup)}
* appropriately.
*
* @author Jake Wharton (jakewharton@gmail.com)
*/
class AdapterWrapper extends BaseAdapter implements StickyListHeadersAdapter {
interface OnHeaderClickListener {
public void onHeaderClick(View header, int itemPosition, long headerId);
}
final StickyListHeadersAdapter mDelegate;
private final List<View> mHeaderCache = new LinkedList<View>();
private final Context mContext;
private Drawable mDivider;
private int mDividerHeight;
private OnHeaderClickListener mOnHeaderClickListener;
private DataSetObserver mDataSetObserver = new DataSetObserver() {
@Override
public void onInvalidated() {
mHeaderCache.clear();
AdapterWrapper.super.notifyDataSetInvalidated();
}
@Override
public void onChanged() {
AdapterWrapper.super.notifyDataSetChanged();
}
};
AdapterWrapper(Context context,
StickyListHeadersAdapter delegate) {
this.mContext = context;
this.mDelegate = delegate;
delegate.registerDataSetObserver(mDataSetObserver);
}
void setDivider(Drawable divider, int dividerHeight) {
this.mDivider = divider;
this.mDividerHeight = dividerHeight;
notifyDataSetChanged();
}
@Override
public boolean areAllItemsEnabled() {
return mDelegate.areAllItemsEnabled();
}
@Override
public boolean isEnabled(int position) {
return mDelegate.isEnabled(position);
}
@Override
public int getCount() {
return mDelegate.getCount();
}
@Override
public Object getItem(int position) {
return mDelegate.getItem(position);
}
@Override
public long getItemId(int position) {
return mDelegate.getItemId(position);
}
@Override
public boolean hasStableIds() {
return mDelegate.hasStableIds();
}
@Override
public int getItemViewType(int position) {
return mDelegate.getItemViewType(position);
}
@Override
public int getViewTypeCount() {
return mDelegate.getViewTypeCount();
}
@Override
public boolean isEmpty() {
return mDelegate.isEmpty();
}
/**
* Will recycle header from {@link WrapperView} if it exists
*/
private void recycleHeaderIfExists(WrapperView wv) {
View header = wv.mHeader;
if (header != null) {
// reset the headers visibility when adding it to the cache
header.setVisibility(View.VISIBLE);
mHeaderCache.add(header);
}
}
/**
* Get a header view. This optionally pulls a header from the supplied
* {@link WrapperView} and will also recycle the divider if it exists.
*/
private View configureHeader(WrapperView wv, final int position) {
View header = wv.mHeader == null ? popHeader() : wv.mHeader;
header = mDelegate.getHeaderView(position, header, wv);
if (header == null) {
throw new NullPointerException("Header view must not be null.");
}
//if the header isn't clickable, the listselector will be drawn on top of the header
header.setClickable(true);
header.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mOnHeaderClickListener != null){
long headerId = mDelegate.getHeaderId(position);
mOnHeaderClickListener.onHeaderClick(v, position, headerId);
}
}
});
return header;
}
private View popHeader() {
if(mHeaderCache.size() > 0) {
return mHeaderCache.remove(0);
}
return null;
}
/** Returns {@code true} if the previous position has the same header ID. */
private boolean previousPositionHasSameHeader(int position) {
return position != 0
&& mDelegate.getHeaderId(position) == mDelegate
.getHeaderId(position - 1);
}
@Override
public WrapperView getView(int position, View convertView, ViewGroup parent) {
WrapperView wv = (convertView == null) ? new WrapperView(mContext) : (WrapperView) convertView;
View item = mDelegate.getView(position, wv.mItem, parent);
View header = null;
if (previousPositionHasSameHeader(position)) {
recycleHeaderIfExists(wv);
} else {
header = configureHeader(wv, position);
}
if((item instanceof Checkable) && !(wv instanceof CheckableWrapperView)) {
// Need to create Checkable subclass of WrapperView for ListView to work correctly
wv = new CheckableWrapperView(mContext);
} else if(!(item instanceof Checkable) && (wv instanceof CheckableWrapperView)) {
wv = new WrapperView(mContext);
}
wv.update(item, header, mDivider, mDividerHeight);
return wv;
}
public void setOnHeaderClickListener(OnHeaderClickListener onHeaderClickListener){
this.mOnHeaderClickListener = onHeaderClickListener;
}
@Override
public boolean equals(Object o) {
return mDelegate.equals(o);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return ((BaseAdapter) mDelegate).getDropDownView(position, convertView, parent);
}
@Override
public int hashCode() {
return mDelegate.hashCode();
}
@Override
public void notifyDataSetChanged() {
((BaseAdapter) mDelegate).notifyDataSetChanged();
}
@Override
public void notifyDataSetInvalidated() {
((BaseAdapter) mDelegate).notifyDataSetInvalidated();
}
@Override
public String toString() {
return mDelegate.toString();
}
@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
return mDelegate.getHeaderView(position, convertView, parent);
}
@Override
public long getHeaderId(int position) {
return mDelegate.getHeaderId(position);
}
}

View File

@ -0,0 +1,11 @@
package se.emilsjolander.stickylistheaders;
public class ApiLevelTooLowException extends RuntimeException {
private static final long serialVersionUID = -5480068364264456757L;
public ApiLevelTooLowException(int versionCode) {
super("Requires API level " + versionCode);
}
}

View File

@ -0,0 +1,31 @@
package se.emilsjolander.stickylistheaders;
import android.content.Context;
import android.widget.Checkable;
/**
* A WrapperView that implements the checkable interface
*
* @author Emil Sjölander
*/
class CheckableWrapperView extends WrapperView implements Checkable {
public CheckableWrapperView(final Context context) {
super(context);
}
@Override
public boolean isChecked() {
return ((Checkable) mItem).isChecked();
}
@Override
public void setChecked(final boolean checked) {
((Checkable) mItem).setChecked(checked);
}
@Override
public void toggle() {
setChecked(!isChecked());
}
}

View File

@ -0,0 +1,32 @@
package se.emilsjolander.stickylistheaders;
import android.content.Context;
import android.widget.SectionIndexer;
class SectionIndexerAdapterWrapper extends
AdapterWrapper implements SectionIndexer {
final SectionIndexer mSectionIndexerDelegate;
SectionIndexerAdapterWrapper(Context context,
StickyListHeadersAdapter delegate) {
super(context, delegate);
mSectionIndexerDelegate = (SectionIndexer) delegate;
}
@Override
public int getPositionForSection(int section) {
return mSectionIndexerDelegate.getPositionForSection(section);
}
@Override
public int getSectionForPosition(int position) {
return mSectionIndexerDelegate.getSectionForPosition(position);
}
@Override
public Object[] getSections() {
return mSectionIndexerDelegate.getSections();
}
}

View File

@ -0,0 +1,38 @@
package se.emilsjolander.stickylistheaders;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
public interface StickyListHeadersAdapter extends ListAdapter {
/**
* Get a View that displays the header data at the specified position in the
* set. You can either create a View manually or inflate it from an XML layout
* file.
*
* @param position
* The position of the item within the adapter's data set of the item whose
* header view we want.
* @param convertView
* The old view to reuse, if possible. Note: You should check that this view is
* non-null and of an appropriate type before using. If it is not possible to
* convert this view to display the correct data, this method can create a new
* view.
* @param parent
* The parent that this view will eventually be attached to.
* @return
* A View corresponding to the data at the specified position.
*/
View getHeaderView(int position, View convertView, ViewGroup parent);
/**
* Get the header id associated with the specified position in the list.
*
* @param position
* The position of the item within the adapter's data set whose header id we
* want.
* @return
* The id of the header at the specified position.
*/
long getHeaderId(int position);
}

View File

@ -0,0 +1,925 @@
package se.emilsjolander.stickylistheaders;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import se.emilsjolander.stickylistheaders.WrapperViewList.LifeCycleListener;
/**
* Even though this is a FrameLayout subclass we it is called a ListView. This
* is because of 2 reasons. 1. It acts like as ListView 2. It used to be a
* ListView subclass and i did not was to change to name causing compatibility
* errors.
*
* @author Emil Sjölander
*/
public class StickyListHeadersListView extends FrameLayout {
public interface OnHeaderClickListener {
public void onHeaderClick(StickyListHeadersListView l, View header,
int itemPosition, long headerId, boolean currentlySticky);
}
/**
* Notifies the listener when the sticky headers top offset has changed.
*/
public interface OnStickyHeaderOffsetChangedListener {
/**
* @param l The view parent
* @param header The currently sticky header being offset.
* This header is not guaranteed to have it's measurements set.
* It is however guaranteed that this view has been measured,
* therefor you should user getMeasured* methods instead of
* get* methods for determining the view's size.
* @param offset The amount the sticky header is offset by towards to top of the screen.
*/
public void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset);
}
/* --- Children --- */
private WrapperViewList mList;
private View mHeader;
/* --- Header state --- */
private Long mHeaderId;
// used to not have to call getHeaderId() all the time
private Integer mHeaderPosition;
private Integer mHeaderOffset;
/* --- Delegates --- */
private OnScrollListener mOnScrollListenerDelegate;
private AdapterWrapper mAdapter;
/* --- Settings --- */
private boolean mAreHeadersSticky = true;
private boolean mClippingToPadding = true;
private boolean mIsDrawingListUnderStickyHeader = true;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
private int mPaddingRight = 0;
private int mPaddingBottom = 0;
/* --- Other --- */
private OnHeaderClickListener mOnHeaderClickListener;
private OnStickyHeaderOffsetChangedListener mOnStickyHeaderOffsetChangedListener;
private AdapterWrapperDataSetObserver mDataSetObserver;
private Drawable mDivider;
private int mDividerHeight;
public StickyListHeadersListView(Context context) {
this(context, null);
}
public StickyListHeadersListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the wrapped list
mList = new WrapperViewList(context);
// null out divider, dividers are handled by adapter so they look good with headers
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
mList.setDivider(null);
mList.setDividerHeight(0);
mList.setVerticalScrollBarEnabled(isVerticalScrollBarEnabled());
mList.setHorizontalScrollBarEnabled(isHorizontalScrollBarEnabled());
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.StickyListHeadersListView, 0, 0);
try {
// -- View attributes --
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, padding);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, padding);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight, padding);
mPaddingBottom = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingBottom, padding);
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight,
mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// -- ListView attributes --
mList.setFadingEdgeLength(a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a
.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint, mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(R.styleable.StickyListHeadersListView_android_fastScrollEnabled,
mList.isFastScrollEnabled()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setFastScrollAlwaysVisible(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollAlwaysVisible,
mList.isFastScrollAlwaysVisible()));
}
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
if (a.hasValue(R.styleable.StickyListHeadersListView_android_listSelector)) {
mList.setSelector(a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector));
}
mList.setScrollingCacheEnabled(a.getBoolean(R.styleable.StickyListHeadersListView_android_scrollingCache,
mList.isScrollingCacheEnabled()));
if (a.hasValue(R.styleable.StickyListHeadersListView_android_divider)) {
mDivider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight,
mDividerHeight);
// -- StickyListHeaders attributes --
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader,
true);
} finally {
a.recycle();
}
}
// attach some listeners to the wrapped list
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureHeader(mHeader);
}
private void ensureHeaderHasCorrectLayoutParams(View header) {
ViewGroup.LayoutParams lp = header.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
lp.height = LayoutParams.WRAP_CONTENT;
}
header.setLayoutParams(lp);
}
private void measureHeader(View header) {
if (header != null) {
final int width = getMeasuredWidth() - mPaddingLeft - mPaddingRight;
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
measureChild(header, parentWidthMeasureSpec,
parentHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
mList.layout(0, 0, mList.getMeasuredWidth(), getHeight());
if (mHeader != null) {
MarginLayoutParams lp = (MarginLayoutParams) mHeader
.getLayoutParams();
int headerTop = lp.topMargin
+ (mClippingToPadding ? mPaddingTop : 0);
// The left parameter must for some reason be set to 0.
// I think it should be set to mPaddingLeft but apparently not
mHeader.layout(mPaddingLeft, headerTop, mHeader.getMeasuredWidth()
+ mPaddingLeft, headerTop + mHeader.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Only draw the list here.
// The header should be drawn right after the lists children are drawn.
// This is done so that the header is above the list items
// but below the list decorators (scroll bars etc).
drawChild(canvas, mList, 0);
}
// Reset values tied the header. also remove header form layout
// This is called in response to the data set or the adapter changing
private void clearHeader() {
if (mHeader != null) {
removeView(mHeader);
mHeader = null;
mHeaderId = null;
mHeaderPosition = null;
mHeaderOffset = null;
// reset the top clipping length
mList.setTopClippingLength(0);
updateHeaderVisibilities();
}
}
private void updateOrClearHeader(int firstVisiblePosition) {
final int adapterCount = mAdapter == null ? 0 : mAdapter.getCount();
if (adapterCount == 0 || !mAreHeadersSticky) {
return;
}
final int headerViewCount = mList.getHeaderViewsCount();
final int realFirstVisibleItem = firstVisiblePosition - headerViewCount;
// It is not a mistake to call getFirstVisiblePosition() here.
// Most of the time getFixedFirstVisibleItem() should be called
// but that does not work great together with getChildAt()
final boolean doesListHaveChildren = mList.getChildCount() != 0;
final boolean isFirstViewBelowTop = doesListHaveChildren && mList
.getFirstVisiblePosition() == 0
&& mList.getChildAt(0).getTop() > (mClippingToPadding ? mPaddingTop : 0);
final boolean isFirstVisibleItemOutsideAdapterRange = realFirstVisibleItem > adapterCount - 1
|| realFirstVisibleItem < 0;
if (!doesListHaveChildren || isFirstVisibleItemOutsideAdapterRange
|| isFirstViewBelowTop) {
clearHeader();
return;
}
updateHeader(realFirstVisibleItem);
}
private void updateHeader(int firstVisiblePosition) {
// check if there is a new header should be sticky
if (mHeaderPosition == null || mHeaderPosition != firstVisiblePosition) {
mHeaderPosition = firstVisiblePosition;
final long headerId = mAdapter.getHeaderId(firstVisiblePosition);
if (mHeaderId == null || mHeaderId != headerId) {
mHeaderId = headerId;
final View header = mAdapter.getHeaderView(mHeaderPosition,
mHeader, this);
if (mHeader != header) {
if (header == null) {
throw new NullPointerException("header may not be null");
}
swapHeader(header);
}
ensureHeaderHasCorrectLayoutParams(mHeader);
measureHeader(mHeader);
// Reset mHeaderOffset to null ensuring
// that it will be set on the header and
// not skipped for performance reasons.
mHeaderOffset = null;
}
}
int headerOffset = 0;
// Calculate new header offset
// Skip looking at the first view. it never matters because it always
// results in a headerOffset = 0
int headerBottom = mHeader.getMeasuredHeight()
+ (mClippingToPadding ? mPaddingTop : 0);
for (int i = 0; i < mList.getChildCount(); i++) {
final View child = mList.getChildAt(i);
final boolean doesChildHaveHeader = child instanceof WrapperView
&& ((WrapperView) child).hasHeader();
final boolean isChildFooter = mList.containsFooterView(child);
if (child.getTop() >= (mClippingToPadding ? mPaddingTop : 0)
&& (doesChildHaveHeader || isChildFooter)) {
headerOffset = Math.min(child.getTop() - headerBottom, 0);
break;
}
}
setHeaderOffet(headerOffset);
if (!mIsDrawingListUnderStickyHeader) {
mList.setTopClippingLength(mHeader.getMeasuredHeight()
+ mHeaderOffset);
}
updateHeaderVisibilities();
}
private void swapHeader(View newHeader) {
if (mHeader != null) {
removeView(mHeader);
}
mHeader = newHeader;
addView(mHeader);
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnHeaderClickListener != null) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, mHeader,
mHeaderPosition, mHeaderId, true);
}
}
});
}
// hides the headers in the list under the sticky header.
// Makes sure the other ones are showing
private void updateHeaderVisibilities() {
int top;
if (mHeader != null) {
top = mHeader.getMeasuredHeight()
+ (mHeaderOffset != null ? mHeaderOffset : 0);
} else {
top = mClippingToPadding ? mPaddingTop : 0;
}
int childCount = mList.getChildCount();
for (int i = 0; i < childCount; i++) {
// ensure child is a wrapper view
View child = mList.getChildAt(i);
if (!(child instanceof WrapperView)) {
continue;
}
// ensure wrapper view child has a header
WrapperView wrapperViewChild = (WrapperView) child;
if (!wrapperViewChild.hasHeader()) {
continue;
}
// update header views visibility
View childHeader = wrapperViewChild.mHeader;
if (wrapperViewChild.getTop() < top) {
if (childHeader.getVisibility() != View.INVISIBLE) {
childHeader.setVisibility(View.INVISIBLE);
}
} else {
if (childHeader.getVisibility() != View.VISIBLE) {
childHeader.setVisibility(View.VISIBLE);
}
}
}
}
// Wrapper around setting the header offset in different ways depending on
// the API version
@SuppressLint("NewApi")
private void setHeaderOffet(int offset) {
if (mHeaderOffset == null || mHeaderOffset != offset) {
mHeaderOffset = offset;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mHeader.setTranslationY(mHeaderOffset);
} else {
MarginLayoutParams params = (MarginLayoutParams) mHeader
.getLayoutParams();
params.topMargin = mHeaderOffset;
mHeader.setLayoutParams(params);
}
if (mOnStickyHeaderOffsetChangedListener != null) {
mOnStickyHeaderOffsetChangedListener
.onStickyHeaderOffsetChanged(this, mHeader, -mHeaderOffset);
}
}
}
private class AdapterWrapperDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
clearHeader();
}
@Override
public void onInvalidated() {
clearHeader();
}
}
private class WrapperListScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScroll(view, firstVisibleItem,
visibleItemCount, totalItemCount);
}
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScrollStateChanged(view,
scrollState);
}
}
}
private class WrapperViewListLifeCycleListener implements LifeCycleListener {
@Override
public void onDispatchDrawOccurred(Canvas canvas) {
// onScroll is not called often at all before froyo
// therefor we need to update the header here as well.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
if (mHeader != null) {
if (mClippingToPadding) {
canvas.save();
canvas.clipRect(0, mPaddingTop, getRight(), getBottom());
drawChild(canvas, mHeader, 0);
canvas.restore();
} else {
drawChild(canvas, mHeader, 0);
}
}
}
}
private class AdapterWrapperHeaderClickHandler implements
AdapterWrapper.OnHeaderClickListener {
@Override
public void onHeaderClick(View header, int itemPosition, long headerId) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, header, itemPosition,
headerId, false);
}
}
private boolean isStartOfSection(int position) {
return position == 0
|| mAdapter.getHeaderId(position) != mAdapter
.getHeaderId(position - 1);
}
private int getHeaderOverlap(int position) {
boolean isStartOfSection = isStartOfSection(position);
if (!isStartOfSection) {
View header = mAdapter.getHeaderView(position, null, mList);
if (header == null) {
throw new NullPointerException("header may not be null");
}
ensureHeaderHasCorrectLayoutParams(header);
measureHeader(header);
return header.getMeasuredHeight();
}
return 0;
}
/* ---------- StickyListHeaders specific API ---------- */
public void setAreHeadersSticky(boolean areHeadersSticky) {
mAreHeadersSticky = areHeadersSticky;
if (!areHeadersSticky) {
clearHeader();
} else {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
// invalidating the list will trigger dispatchDraw()
mList.invalidate();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Use areHeadersSticky() method instead
*/
@Deprecated
public boolean getAreHeadersSticky() {
return areHeadersSticky();
}
public void setDrawingListUnderStickyHeader(
boolean drawingListUnderStickyHeader) {
mIsDrawingListUnderStickyHeader = drawingListUnderStickyHeader;
// reset the top clipping length
mList.setTopClippingLength(0);
}
public boolean isDrawingListUnderStickyHeader() {
return mIsDrawingListUnderStickyHeader;
}
public void setOnHeaderClickListener(OnHeaderClickListener listener) {
mOnHeaderClickListener = listener;
if (mAdapter != null) {
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
}
}
public void setOnStickyHeaderOffsetChangedListener(OnStickyHeaderOffsetChangedListener listener) {
mOnStickyHeaderOffsetChangedListener = listener;
}
public View getListChildAt(int index) {
return mList.getChildAt(index);
}
public int getListChildCount() {
return mList.getChildCount();
}
/**
* Use the method with extreme caution!! Changing any values on the
* underlying ListView might break everything.
*
* @return the ListView backing this view.
*/
public ListView getWrappedList() {
return mList;
}
/* ---------- ListView delegate methods ---------- */
public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
}
public StickyListHeadersAdapter getAdapter() {
return mAdapter == null ? null : mAdapter.mDelegate;
}
public void setDivider(Drawable divider) {
mDivider = divider;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public void setDividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public Drawable getDivider() {
return mDivider;
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
mOnScrollListenerDelegate = onScrollListener;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mList.setOnItemClickListener(listener);
}
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
mList.setOnItemLongClickListener(listener);
}
public void addHeaderView(View v, Object data, boolean isSelectable) {
mList.addHeaderView(v, data, isSelectable);
}
public void addHeaderView(View v) {
mList.addHeaderView(v);
}
public void removeHeaderView(View v) {
mList.removeHeaderView(v);
}
public int getHeaderViewsCount() {
return mList.getHeaderViewsCount();
}
public void addFooterView(View v) {
mList.addFooterView(v);
}
public void removeFooterView(View v) {
mList.removeFooterView(v);
}
public int getFooterViewsCount() {
return mList.getFooterViewsCount();
}
public void setEmptyView(View v) {
mList.setEmptyView(v);
}
public View getEmptyView() {
return mList.getEmptyView();
}
@Override
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
mList.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
}
@Override
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
mList.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollBy(int distance, int duration) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollBy(distance, duration);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollByOffset(int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
mList.smoothScrollByOffset(offset);
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mList.smoothScrollToPosition(position);
} else {
int offset = mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset);
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position, int boundPosition) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollToPosition(position, boundPosition);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset,
int duration) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset, duration);
}
public void setSelection(int position) {
setSelectionFromTop(position, 0);
}
public void setSelectionAfterHeaderView() {
mList.setSelectionAfterHeaderView();
}
public void setSelectionFromTop(int position, int y) {
y += mAdapter == null ? 0 : getHeaderOverlap(position);
y -= mClippingToPadding ? 0 : mPaddingTop;
mList.setSelectionFromTop(position, y);
}
public void setSelector(Drawable sel) {
mList.setSelector(sel);
}
public void setSelector(int resID) {
mList.setSelector(resID);
}
public int getFirstVisiblePosition() {
return mList.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
return mList.getLastVisiblePosition();
}
public void setChoiceMode(int choiceMode) {
mList.setChoiceMode(choiceMode);
}
public void setItemChecked(int position, boolean value) {
mList.setItemChecked(position, value);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemCount() {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
return mList.getCheckedItemCount();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
requireSdkVersion(Build.VERSION_CODES.FROYO);
return mList.getCheckedItemIds();
}
public int getCheckedItemPosition() {
return mList.getCheckedItemPosition();
}
public SparseBooleanArray getCheckedItemPositions() {
return mList.getCheckedItemPositions();
}
public int getCount() {
return mList.getCount();
}
public Object getItemAtPosition(int position) {
return mList.getItemAtPosition(position);
}
public long getItemIdAtPosition(int position) {
return mList.getItemIdAtPosition(position);
}
@Override
public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
mList.setOnCreateContextMenuListener(l);
}
@Override
public boolean showContextMenu() {
return mList.showContextMenu();
}
public void invalidateViews() {
mList.invalidateViews();
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (mList != null) {
mList.setClipToPadding(clipToPadding);
}
mClippingToPadding = clipToPadding;
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
mPaddingLeft = left;
mPaddingTop = top;
mPaddingRight = right;
mPaddingBottom = bottom;
if (mList != null) {
mList.setPadding(left, top, right, bottom);
}
super.setPadding(0, 0, 0, 0);
requestLayout();
}
/*
* Overrides an @hide method in View
*/
protected void recomputePadding() {
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
@Override
public int getPaddingLeft() {
return mPaddingLeft;
}
@Override
public int getPaddingTop() {
return mPaddingTop;
}
@Override
public int getPaddingRight() {
return mPaddingRight;
}
@Override
public int getPaddingBottom() {
return mPaddingBottom;
}
public void setFastScrollEnabled(boolean fastScrollEnabled) {
mList.setFastScrollEnabled(fastScrollEnabled);
}
/**
* @throws ApiLevelTooLowException on pre-Honeycomb device.
* @see android.widget.AbsListView#setFastScrollAlwaysVisible(boolean)
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setFastScrollAlwaysVisible(boolean alwaysVisible) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
mList.setFastScrollAlwaysVisible(alwaysVisible);
}
/**
* @return true if the fast scroller will always show. False on pre-Honeycomb devices.
* @see android.widget.AbsListView#isFastScrollAlwaysVisible()
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean isFastScrollAlwaysVisible() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return false;
}
return mList.isFastScrollAlwaysVisible();
}
public void setScrollBarStyle(int style) {
mList.setScrollBarStyle(style);
}
public int getScrollBarStyle() {
return mList.getScrollBarStyle();
}
private void requireSdkVersion(int versionCode) {
if (Build.VERSION.SDK_INT < versionCode) {
throw new ApiLevelTooLowException(versionCode);
}
}
public int getPositionForView(View view) {
return mList.getPositionForView(view);
}
}

View File

@ -0,0 +1,150 @@
package se.emilsjolander.stickylistheaders;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
/**
*
* the view that wrapps a divider header and a normal list item. The listview sees this as 1 item
*
* @author Emil Sjölander
*/
public class WrapperView extends ViewGroup {
View mItem;
Drawable mDivider;
int mDividerHeight;
View mHeader;
int mItemTop;
WrapperView(Context c) {
super(c);
}
public boolean hasHeader() {
return mHeader != null;
}
public View getItem() {
return mItem;
}
public View getHeader() {
return mHeader;
}
void update(View item, View header, Drawable divider, int dividerHeight) {
//every wrapperview must have a list item
if (item == null) {
throw new NullPointerException("List view item must not be null.");
}
//only remove the current item if it is not the same as the new item. this can happen if wrapping a recycled view
if (this.mItem != item) {
removeView(this.mItem);
this.mItem = item;
final ViewParent parent = item.getParent();
if(parent != null && parent != this) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(item);
}
}
addView(item);
}
//same logik as above but for the header
if (this.mHeader != header) {
if (this.mHeader != null) {
removeView(this.mHeader);
}
this.mHeader = header;
if (header != null) {
addView(header);
}
}
if (this.mDivider != divider) {
this.mDivider = divider;
this.mDividerHeight = dividerHeight;
invalidate();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth,
MeasureSpec.EXACTLY);
int measuredHeight = 0;
//measure header or divider. when there is a header visible it acts as the divider
if (mHeader != null) {
ViewGroup.LayoutParams params = mHeader.getLayoutParams();
if (params != null && params.height > 0) {
mHeader.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY));
} else {
mHeader.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
}
measuredHeight += mHeader.getMeasuredHeight();
} else if (mDivider != null) {
measuredHeight += mDividerHeight;
}
//measure item
ViewGroup.LayoutParams params = mItem.getLayoutParams();
if (params != null && params.height > 0) {
mItem.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY));
} else {
mItem.measure(childWidthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
}
measuredHeight += mItem.getMeasuredHeight();
setMeasuredDimension(measuredWidth, measuredHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
l = 0;
t = 0;
r = getWidth();
b = getHeight();
if (mHeader != null) {
int headerHeight = mHeader.getMeasuredHeight();
mHeader.layout(l, t, r, headerHeight);
mItemTop = headerHeight;
mItem.layout(l, headerHeight, r, b);
} else if (mDivider != null) {
mDivider.setBounds(l, t, r, mDividerHeight);
mItemTop = mDividerHeight;
mItem.layout(l, mDividerHeight, r, b);
} else {
mItemTop = t;
mItem.layout(l, t, r, b);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mHeader == null && mDivider != null) {
// Drawable.setBounds() does not seem to work pre-honeycomb. So have
// to do this instead
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
canvas.clipRect(0, 0, getWidth(), mDividerHeight);
}
mDivider.draw(canvas);
}
}
}

View File

@ -0,0 +1,175 @@
package se.emilsjolander.stickylistheaders;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
class WrapperViewList extends ListView {
interface LifeCycleListener {
void onDispatchDrawOccurred(Canvas canvas);
}
private LifeCycleListener mLifeCycleListener;
private List<View> mFooterViews;
private int mTopClippingLength;
private Rect mSelectorRect = new Rect();// for if reflection fails
private Field mSelectorPositionField;
private boolean mClippingToPadding = true;
public WrapperViewList(Context context) {
super(context);
// Use reflection to be able to change the size/position of the list
// selector so it does not come under/over the header
try {
Field selectorRectField = AbsListView.class.getDeclaredField("mSelectorRect");
selectorRectField.setAccessible(true);
mSelectorRect = (Rect) selectorRectField.get(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
mSelectorPositionField = AbsListView.class.getDeclaredField("mSelectorPosition");
mSelectorPositionField.setAccessible(true);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public boolean performItemClick(View view, int position, long id) {
if (view instanceof WrapperView) {
view = ((WrapperView) view).mItem;
}
return super.performItemClick(view, position, id);
}
private void positionSelectorRect() {
if (!mSelectorRect.isEmpty()) {
int selectorPosition = getSelectorPosition();
if (selectorPosition >= 0) {
int firstVisibleItem = getFixedFirstVisibleItem();
View v = getChildAt(selectorPosition - firstVisibleItem);
if (v instanceof WrapperView) {
WrapperView wrapper = ((WrapperView) v);
mSelectorRect.top = wrapper.getTop() + wrapper.mItemTop;
}
}
}
}
private int getSelectorPosition() {
if (mSelectorPositionField == null) { // not all supported andorid
// version have this variable
for (int i = 0; i < getChildCount(); i++) {
if (getChildAt(i).getBottom() == mSelectorRect.bottom) {
return i + getFixedFirstVisibleItem();
}
}
} else {
try {
return mSelectorPositionField.getInt(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return -1;
}
@Override
protected void dispatchDraw(Canvas canvas) {
positionSelectorRect();
if (mTopClippingLength != 0) {
canvas.save();
Rect clipping = canvas.getClipBounds();
clipping.top = mTopClippingLength;
canvas.clipRect(clipping);
super.dispatchDraw(canvas);
canvas.restore();
} else {
super.dispatchDraw(canvas);
}
mLifeCycleListener.onDispatchDrawOccurred(canvas);
}
void setLifeCycleListener(LifeCycleListener lifeCycleListener) {
mLifeCycleListener = lifeCycleListener;
}
@Override
public void addFooterView(View v) {
super.addFooterView(v);
if (mFooterViews == null) {
mFooterViews = new ArrayList<View>();
}
mFooterViews.add(v);
}
@Override
public boolean removeFooterView(View v) {
if (super.removeFooterView(v)) {
mFooterViews.remove(v);
return true;
}
return false;
}
boolean containsFooterView(View v) {
if (mFooterViews == null) {
return false;
}
return mFooterViews.contains(v);
}
void setTopClippingLength(int topClipping) {
mTopClippingLength = topClipping;
}
int getFixedFirstVisibleItem() {
int firstVisibleItem = getFirstVisiblePosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return firstVisibleItem;
}
// first getFirstVisiblePosition() reports items
// outside the view sometimes on old versions of android
for (int i = 0; i < getChildCount(); i++) {
if (getChildAt(i).getBottom() >= 0) {
firstVisibleItem += i;
break;
}
}
// work around to fix bug with firstVisibleItem being to high
// because list view does not take clipToPadding=false into account
// on old versions of android
if (!mClippingToPadding && getPaddingTop() > 0 && firstVisibleItem > 0) {
if (getChildAt(0).getTop() > 0) {
firstVisibleItem -= 1;
}
}
return firstVisibleItem;
}
@Override
public void setClipToPadding(boolean clipToPadding) {
mClippingToPadding = clipToPadding;
super.setClipToPadding(clipToPadding);
}
}

View File

@ -0,0 +1,27 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="se.emilsjolander.stickylistheaders"
android:versionCode="2"
android:versionName="2.0">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
android:supportsRtl="true">
<activity
android:name=".TestActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,23 @@
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile project(':library')
compile 'com.android.support:appcompat-v7:19.0.+'
compile 'com.android.support:support-v4:19.0.0'
}
android {
compileSdkVersion 19
buildToolsVersion '19.0.0'
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
}
}

View File

@ -0,0 +1,15 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19
android.library.reference.1=../library

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@color/header_pressed" />
<item android:drawable="@color/header_normal" />
</selector>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/header_selector" >
<se.emilsjolander.stickylistheaders.views.UnderlineTextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|left"
android:padding="5dp"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:text="@string/app_name"
android:layout_width="match_parent"
android:layout_height="700dip"
android:gravity="center"
android:layout_gravity="center"/>
</FrameLayout>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:text="@string/app_name"
android:layout_width="match_parent"
android:layout_height="400dip"
android:gravity="center"
android:layout_gravity="center"/>
</FrameLayout>

View File

@ -0,0 +1,114 @@
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<se.emilsjolander.stickylistheaders.StickyListHeadersListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:drawSelectorOnTop="true"
android:padding="16dp"
android:scrollbarStyle="outsideOverlay"
android:fastScrollEnabled="true"/>
<TextView
android:id="@+id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/empty"
android:textSize="30sp"
android:visibility="gone"/>
</FrameLayout>
<ScrollView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:padding="5dp"
android:scrollbars="none"
android:clickable="true"
android:background="@android:color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<se.emilsjolander.stickylistheaders.views.UnderlineTextView
style="@style/MenuSectionHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|left"
android:text="@string/actions"
android:textStyle="bold"/>
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="left|center_vertical"
android:text="@string/restore_list"
android:id="@+id/restore_button"/>
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="left|center_vertical"
android:text="@string/update_list"
android:id="@+id/update_button"/>
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="left|center_vertical"
android:id="@+id/clear_button"
android:text="@string/clear_list"/>
<se.emilsjolander.stickylistheaders.views.UnderlineTextView
style="@style/MenuSectionHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|left"
android:text="@string/options"
android:textStyle="bold"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sticky_header"
android:id="@+id/sticky_checkBox"
android:checked="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fade_header"
android:id="@+id/fade_checkBox"
android:checked="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/draw_behind_header"
android:id="@+id/draw_behind_checkBox"
android:checked="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fast_scroll"
android:id="@+id/fast_scroll_checkBox"
android:checked="true"/>
</LinearLayout>
</ScrollView>
</android.support.v4.widget.DrawerLayout>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="20dp"
android:paddingTop="20dp" />

View File

@ -0,0 +1,230 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries">
<item>Afghanistan</item>
<item>Albania</item>
<item>Algeria</item>
<item>Andorra</item>
<item>Angola</item>
<item>Antigua &amp; Barbuda</item>
<item>Argentina</item>
<item>Armenia</item>
<item>Australia</item>
<item>Austria</item>
<item>Azerbaijan</item>
<item>Bahamas</item>
<item>Bahrain</item>
<item>Bangladesh</item>
<item>Barbados</item>
<item>Belarus</item>
<item>Belgium</item>
<item>Belize</item>
<item>Benin</item>
<item>Bhutan</item>
<item>Bolivia</item>
<item>Bosnia and Herzegovina</item>
<item>Botswana</item>
<item>Brazil</item>
<item>Brunei</item>
<item>Bulgaria</item>
<item>Burkina Faso</item>
<item>Burma</item>
<item>Burundi</item>
<item>Cambodia</item>
<item>Cameroon</item>
<item>Canada</item>
<item>Cape Verde</item>
<item>Central African Republic</item>
<item>Chad</item>
<item>Chile</item>
<item>China</item>
<item>Colombia</item>
<item>Comoros</item>
<item>Congo, Democratic Republic of the</item>
<item>Congo, Republic of the</item>
<item>Costa Rica</item>
<item>Cote d\'voire</item>
<item>Croatia</item>
<item>Cuba</item>
<item>Cyprus</item>
<item>Czech Republic</item>
<item>Denmark</item>
<item>Djibouti</item>
<item>Dominica</item>
<item>Dominican Republic</item>
<item>Ecuador</item>
<item>Egypt</item>
<item>El Salvador</item>
<item>Equatorial Guinea</item>
<item>Eritrea</item>
<item>Estonia</item>
<item>Ethiopia</item>
<item>Fiji</item>
<item>Finland</item>
<item>France</item>
<item>Gabon</item>
<item>Gambia, The</item>
<item>Georgia</item>
<item>Ghana</item>
<item>Greece</item>
<item>Grenada</item>
<item>Guatemala</item>
<item>Guinea</item>
<item>Guinea-Bissau</item>
<item>Guyana</item>
<item>Haiti</item>
<item>Holy See</item>
<item>Honduras</item>
<item>Hong Kong</item>
<item>Hungary</item>
<item>Iceland</item>
<item>India</item>
<item>Indonesia</item>
<item>Iran</item>
<item>Iraq</item>
<item>Ireland</item>
<item>Israel</item>
<item>Italy</item>
<item>Jamaica</item>
<item>Japan</item>
<item>Jordan</item>
<item>Kazakhstan</item>
<item>Kenya</item>
<item>Kiribati</item>
<item>Korea, North</item>
<item>Korea, South</item>
<item>Kosovo</item>
<item>Kuwait</item>
<item>Kyrgyzstan</item>
<item>Laos</item>
<item>Latvia</item>
<item>Lebanon</item>
<item>Lesotho</item>
<item>Liberia</item>
<item>Libya</item>
<item>Liechtenstein</item>
<item>Lithuania</item>
<item>Luxembourg</item>
<item>Macau</item>
<item>Macedonia</item>
<item>Madagascar</item>
<item>Malawi</item>
<item>Malaysia</item>
<item>Maldives</item>
<item>Mali</item>
<item>Malta</item>
<item>Marshall Islands</item>
<item>Mauritania</item>
<item>Mauritius</item>
<item>Mexico</item>
<item>Micronesia</item>
<item>Moldova</item>
<item>Monaco</item>
<item>Mongolia</item>
<item>Montenegro</item>
<item>Morocco</item>
<item>Mozambique</item>
<item>Namibia</item>
<item>Nauru</item>
<item>Nepal</item>
<item>Netherlands</item>
<item>Netherlands Antilles</item>
<item>New Zealand</item>
<item>Nicaragua</item>
<item>Niger</item>
<item>Nigeria</item>
<item>North Korea</item>
<item>Norway</item>
<item>Oman</item>
<item>Pakistan</item>
<item>Palau</item>
<item>Palestinian Territories</item>
<item>Panama</item>
<item>Papua New Guinea</item>
<item>Paraguay</item>
<item>Peru</item>
<item>Philippines</item>
<item>Poland</item>
<item>Portugal</item>
<item>Qatar</item>
<item>Romania</item>
<item>Russia</item>
<item>Rwanda</item>
<item>Saint Kitts and Nevis</item>
<item>Saint Lucia</item>
<item>Saint Vincent and the Grenadines</item>
<item>Samoa</item>
<item>San Marino</item>
<item>Sao Tome and Principe</item>
<item>Saudi Arabia</item>
<item>Senegal</item>
<item>Serbia</item>
<item>Seychelles</item>
<item>Sierra Leone</item>
<item>Singapore</item>
<item>Slovakia</item>
<item>Slovenia</item>
<item>Solomon Islands</item>
<item>Somalia</item>
<item>South Africa</item>
<item>South Korea</item>
<item>South Sudan</item>
<item>Spain</item>
<item>Sri Lanka</item>
<item>Sudan</item>
<item>Suriname</item>
<item>Swaziland</item>
<item>Sweden</item>
<item>Switzerland</item>
<item>Syria</item>
<item>Taiwan</item>
<item>Tajikistan</item>
<item>Tanzania</item>
<item>Thailand </item>
<item>Timor-Leste</item>
<item>Togo</item>
<item>Tonga</item>
<item>Trinidad and Tobago</item>
<item>Tunisia</item>
<item>Turkey</item>
<item>Turkmenistan</item>
<item>Tuvalu</item>
<item>Uganda</item>
<item>Ukraine</item>
<item>United Arab Emirates</item>
<item>United Kingdom</item>
<item>Uruguay</item>
<item>Uzbekistan</item>
<item>Vanuatu</item>
<item>Venezuela</item>
<item>Vietnam</item>
<item>Yemen</item>
<item>Zambia</item>
<item>Zimbabwe</item>
</string-array>
</resources>

View File

@ -0,0 +1,7 @@
<resources>
<color name="header_normal">#ffe74c3c</color>
<color name="header_pressed">#ffc0392b</color>
<color name="menu_section_header">#FFDDDDDD</color>
</resources>

View File

@ -0,0 +1,20 @@
<resources>
<string name="app_name">StickyListHeaders Sample</string>
<string name="restore">Restore</string>
<string name="update">Update</string>
<string name="clear">Clear</string>
<string name="empty">Empty Adapter</string>
<string name="drawer_open">Drawer Open</string>
<string name="drawer_close">Drawer Close</string>
<string name="options">OPTIONS</string>
<string name="actions">ACTIONS</string>
<string name="restore_list">Restore list</string>
<string name="update_list">Update list</string>
<string name="clear_list">Clear list</string>
<string name="sticky_header">Sticky header</string>
<string name="fade_header">Fade header</string>
<string name="draw_behind_header">Draw behind header</string>
<string name="fast_scroll">Fast scroll</string>
</resources>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MenuSectionHeader">
<item name="android:padding">5dp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/menu_section_header</item>
<item name="android:textSize">14sp</item>
</style>
</resources>

View File

@ -0,0 +1,169 @@
package se.emilsjolander.stickylistheaders;
import android.annotation.TargetApi;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* @author Emil Sjölander
*/
public class TestActivity extends ActionBarActivity implements
AdapterView.OnItemClickListener, StickyListHeadersListView.OnHeaderClickListener,
StickyListHeadersListView.OnStickyHeaderOffsetChangedListener {
private TestBaseAdapter mAdapter;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private boolean fadeHeader = true;
private StickyListHeadersListView stickyList;
private Button restoreButton;
private Button updateButton;
private Button clearButton;
private CheckBox stickyCheckBox;
private CheckBox fadeCheckBox;
private CheckBox drawBehindCheckBox;
private CheckBox fastScrollCheckBox;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new TestBaseAdapter(this);
stickyList = (StickyListHeadersListView) findViewById(R.id.list);
stickyList.setOnItemClickListener(this);
stickyList.setOnHeaderClickListener(this);
stickyList.setOnStickyHeaderOffsetChangedListener(this);
// mStickyList.addHeaderView(inflater.inflate(R.layout.list_header, null));
// mStickyList.addFooterView(inflater.inflate(R.layout.list_footer, null));
stickyList.setEmptyView(findViewById(R.id.empty));
stickyList.setDrawingListUnderStickyHeader(true);
stickyList.setAreHeadersSticky(true);
stickyList.setAdapter(mAdapter);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
restoreButton = (Button) findViewById(R.id.restore_button);
restoreButton.setOnClickListener(buttonListener);
updateButton = (Button) findViewById(R.id.update_button);
updateButton.setOnClickListener(buttonListener);
clearButton = (Button) findViewById(R.id.clear_button);
clearButton.setOnClickListener(buttonListener);
stickyCheckBox = (CheckBox) findViewById(R.id.sticky_checkBox);
stickyCheckBox.setOnCheckedChangeListener(checkBoxListener);
fadeCheckBox = (CheckBox) findViewById(R.id.fade_checkBox);
fadeCheckBox.setOnCheckedChangeListener(checkBoxListener);
drawBehindCheckBox = (CheckBox) findViewById(R.id.draw_behind_checkBox);
drawBehindCheckBox.setOnCheckedChangeListener(checkBoxListener);
fastScrollCheckBox = (CheckBox) findViewById(R.id.fast_scroll_checkBox);
fastScrollCheckBox.setOnCheckedChangeListener(checkBoxListener);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.sticky_checkBox:
stickyList.setAreHeadersSticky(isChecked);
break;
case R.id.fade_checkBox:
fadeHeader = isChecked;
break;
case R.id.draw_behind_checkBox:
stickyList.setDrawingListUnderStickyHeader(isChecked);
break;
case R.id.fast_scroll_checkBox:
stickyList.setFastScrollEnabled(isChecked);
stickyList.setFastScrollAlwaysVisible(isChecked);
break;
}
}
};
View.OnClickListener buttonListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.restore_button:
mAdapter.restore();
break;
case R.id.update_button:
mAdapter.notifyDataSetChanged();
break;
case R.id.clear_button:
mAdapter.clear();
break;
}
}
};
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(this, "Item " + position + " clicked!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onHeaderClick(StickyListHeadersListView l, View header,
int itemPosition, long headerId, boolean currentlySticky) {
Toast.makeText(this, "Header " + headerId + " currentlySticky ? " + currentlySticky,
Toast.LENGTH_SHORT).show();
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset) {
if (fadeHeader && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
}
}
}

View File

@ -0,0 +1,169 @@
package se.emilsjolander.stickylistheaders;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;
/**
* @author Emil Sjölander
*/
public class TestBaseAdapter extends BaseAdapter implements
StickyListHeadersAdapter, SectionIndexer {
private final Context mContext;
private String[] mCountries;
private int[] mSectionIndices;
private Character[] mSectionLetters;
private LayoutInflater mInflater;
public TestBaseAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(context);
mCountries = context.getResources().getStringArray(R.array.countries);
mSectionIndices = getSectionIndices();
mSectionLetters = getSectionLetters();
}
private int[] getSectionIndices() {
ArrayList<Integer> sectionIndices = new ArrayList<Integer>();
char lastFirstChar = mCountries[0].charAt(0);
sectionIndices.add(0);
for (int i = 1; i < mCountries.length; i++) {
if (mCountries[i].charAt(0) != lastFirstChar) {
lastFirstChar = mCountries[i].charAt(0);
sectionIndices.add(i);
}
}
int[] sections = new int[sectionIndices.size()];
for (int i = 0; i < sectionIndices.size(); i++) {
sections[i] = sectionIndices.get(i);
}
return sections;
}
private Character[] getSectionLetters() {
Character[] letters = new Character[mSectionIndices.length];
for (int i = 0; i < mSectionIndices.length; i++) {
letters[i] = mCountries[mSectionIndices[i]].charAt(0);
}
return letters;
}
@Override
public int getCount() {
return mCountries.length;
}
@Override
public Object getItem(int position) {
return mCountries[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.test_list_item_layout, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(mCountries[position]);
return convertView;
}
@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
if (convertView == null) {
holder = new HeaderViewHolder();
convertView = mInflater.inflate(R.layout.header, parent, false);
holder.text = (TextView) convertView.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
// set header text as first char in name
CharSequence headerChar = mCountries[position].subSequence(0, 1);
holder.text.setText(headerChar);
return convertView;
}
/**
* Remember that these have to be static, postion=1 should always return
* the same Id that is.
*/
@Override
public long getHeaderId(int position) {
// return the first character of the country as ID because this is what
// headers are based upon
return mCountries[position].subSequence(0, 1).charAt(0);
}
@Override
public int getPositionForSection(int section) {
if (section >= mSectionIndices.length) {
section = mSectionIndices.length - 1;
} else if (section < 0) {
section = 0;
}
return mSectionIndices[section];
}
@Override
public int getSectionForPosition(int position) {
for (int i = 0; i < mSectionIndices.length; i++) {
if (position < mSectionIndices[i]) {
return i - 1;
}
}
return mSectionIndices.length - 1;
}
@Override
public Object[] getSections() {
return mSectionLetters;
}
public void clear() {
mCountries = new String[0];
mSectionIndices = new int[0];
mSectionLetters = new Character[0];
notifyDataSetChanged();
}
public void restore() {
mCountries = mContext.getResources().getStringArray(R.array.countries);
mSectionIndices = getSectionIndices();
mSectionLetters = getSectionLetters();
notifyDataSetChanged();
}
class HeaderViewHolder {
TextView text;
}
class ViewHolder {
TextView text;
}
}

View File

@ -0,0 +1,50 @@
package se.emilsjolander.stickylistheaders.views;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* @author Eric Frohnhoefer
*/
public class UnderlineTextView extends TextView {
private final Paint mPaint = new Paint();
private int mUnderlineHeight = 0;
public UnderlineTextView(Context context) {
this(context, null);
}
public UnderlineTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public UnderlineTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
Resources r = getResources();
mUnderlineHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, r.getDisplayMetrics());
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom + mUnderlineHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the underline the same color as the text
mPaint.setColor(getTextColors().getDefaultColor());
canvas.drawRect(0, getHeight() - mUnderlineHeight, getWidth(), getHeight(), mPaint);
}
}

View File

@ -0,0 +1,2 @@
include 'library'
include 'sample'

View File

@ -1,3 +1,4 @@
include ':OpenPGP-Keychain'
include ':libraries:ActionBarSherlock'
include ':libraries:HtmlTextView'
include ':libraries:HtmlTextView'
include ':libraries:StickyListHeaders:library'