下面列出了android.widget.Filterable#android.widget.ListAdapter 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void setListAdapter(ListAdapter adapter) {
if (adapter == null) {
super.setListAdapter(null);
} else {
List<Header> headers = null;
try {
Method method = PreferenceActivity.class.getDeclaredMethod("getHeaders");
method.setAccessible(true);
headers = (List<Header>) method.invoke(this);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
super.setListAdapter(new HeaderAdapter(this, headers));
}
}
@Override
public void setAdapter(ListAdapter adapter) {
// assert adapter in debug mode
if (BuildConfig.DEBUG && adapter != null) {
if (!(adapter instanceof PinnedSectionListAdapter))
throw new IllegalArgumentException("Does your adapter implement PinnedSectionListAdapter?");
if (adapter.getViewTypeCount() < 2)
throw new IllegalArgumentException("Does your adapter handle at least two types" +
" of views in getViewTypeCount() method: items and sections?");
}
// unregister observer at old adapter and register on new one
ListAdapter oldAdapter = getAdapter();
if (oldAdapter != null) oldAdapter.unregisterDataSetObserver(mDataSetObserver);
if (adapter != null) adapter.registerDataSetObserver(mDataSetObserver);
// destroy pinned shadow, if new adapter is not same as old one
if (oldAdapter != adapter) destroyPinnedShadow();
super.setAdapter(adapter);
}
@Override
public <T extends ListAdapter & Filterable> void setAdapter(final T adapter)
{
super.setAdapter(adapter);
((BaseRecipientAdapter)adapter).registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver()
{
@Override
public void onChanged(final List<RecipientEntry> entries)
{
// Scroll the chips field to the top of the screen so
// that the user can see as many results as possible.
if(entries!=null&&entries.size()>0)
scrollBottomIntoView();
}
});
}
public void setAdapter(ListAdapter adapter) {
// mSwipeRefreshLayout.setRefreshing(false);
// adapter.registerDataSetObserver(new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// mSwipeRefreshLayout.setRefreshing(false);
//
// }
// });
mBasicUltimateListView.setAdapter(adapter);
// if ((adapter == null || adapter.getCount() == 0) && mEmptyId != 0) {
// mEmpty.setVisibility(View.VISIBLE);
// }
}
public HeaderViewListAdapter(ArrayList<StaggeredGridView.FixedViewInfo> headerViewInfos,
ArrayList<StaggeredGridView.FixedViewInfo> footerViewInfos,
ListAdapter adapter) {
mAdapter = adapter;
mIsFilterable = adapter instanceof Filterable;
if (headerViewInfos == null) {
mHeaderViewInfos = EMPTY_INFO_LIST;
} else {
mHeaderViewInfos = headerViewInfos;
}
if (footerViewInfos == null) {
mFooterViewInfos = EMPTY_INFO_LIST;
} else {
mFooterViewInfos = footerViewInfos;
}
mAreAllFixedViewsSelectable =
areAllListInfosSelectable(mHeaderViewInfos)
&& areAllListInfosSelectable(mFooterViewInfos);
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
public void run() {
if (mDataChanged) return;
final ListAdapter adapter = mAdapter;
final int motionPosition = mClickMotionPosition;
if (adapter != null && mItemCount > 0 &&
motionPosition != INVALID_POSITION &&
motionPosition < adapter.getCount() && sameWindow()) {
final View view = getChildAt(motionPosition); // a fix by @pboos
if (view != null) {
final int clickPosition = motionPosition + mFirstPosition;
performItemClick(view, clickPosition, adapter.getItemId(clickPosition));
}
}
}
/**
* Add a fixed view to appear at the top of the grid. If addHeaderView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p/>
* NOTE: Call this before calling setAdapter. This is so HeaderGridView can wrap
* the supplied cursor with one that will also account for header views.
*
* @param v The view to add.
* @param data Data to associate with this view
* @param isSelectable whether the item is selectable
*/
public void addHeaderView(View v, Object data, boolean isSelectable) {
ListAdapter adapter = getAdapter();
if (adapter != null && !(adapter instanceof HeaderViewGridAdapter)) {
throw new IllegalStateException(
"Cannot add header view to grid -- setAdapter has already been called.");
}
FixedViewInfo info = new FixedViewInfo();
FrameLayout fl = new FullWidthFixedViewLayout(getContext());
fl.addView(v);
info.view = v;
info.viewContainer = fl;
info.data = data;
info.isSelectable = isSelectable;
mHeaderViewInfos.add(info);
// in the case of re-adding a header view, or adding one later on,
// we need to notify the observer
if (adapter != null) {
((HeaderViewGridAdapter) adapter).notifyDataSetChanged();
}
}
@Override
public void setAdapter(ListAdapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mAdapterDataObserver);
}
if (adapter != null) {
// Clear so we can notify again as we run out of data
mHasNotifiedRunningLowOnData = false;
mAdapter = adapter;
mAdapter.registerDataSetObserver(mAdapterDataObserver);
}
initializeRecycledViewCache(mAdapter.getViewTypeCount());
reset();
}
AdapterWrapper(ListAdapter adapter)
{
super();
mAdapter = adapter;
mAdapter.registerDataSetObserver(new DataSetObserver()
{
public void onChanged()
{
notifyDataSetChanged();
}
public void onInvalidated()
{
notifyDataSetInvalidated();
}
});
}
/**
* Updates UI to indicate that retrieval of the offers completed successfully or failed.
*/
@Override
protected void onPostExecute(CollectionResponseOffer result) {
if (result == null || result.getItems() == null || result.getItems().size() < 1) {
if (result == null) {
offersListLabel.setText(R.string.failedToRetrieveOffers);
} else {
offersListLabel.setText(R.string.noOffers);
}
offersList.setAdapter(null);
return;
}
offersListLabel.setText(R.string.offers);
ListAdapter offersListAdapter = createOfferListAdapter(result.getItems());
offersList.setAdapter(offersListAdapter);
}
/**
* Add a fixed view to appear at the top of the grid. If addHeaderView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p>
* NOTE: Call this before calling setAdapter. This is so HeaderGridView can wrap
* the supplied cursor with one that will also account for header views.
*
* @param v The view to add.
* @param data Data to associate with this view
* @param isSelectable whether the item is selectable
*/
public void addHeaderView(View v, Object data, boolean isSelectable) {
ListAdapter adapter = getAdapter();
if (adapter != null && ! (adapter instanceof HeaderViewGridAdapter)) {
throw new IllegalStateException(
"Cannot add header view to grid -- setAdapter has already been called.");
}
FixedViewInfo info = new FixedViewInfo();
FrameLayout fl = new FullWidthFixedViewLayout(getContext());
fl.addView(v);
info.view = v;
info.viewContainer = fl;
info.data = data;
info.isSelectable = isSelectable;
mHeaderViewInfos.add(info);
// in the case of re-adding a header view, or adding one later on,
// we need to notify the observer
if (adapter != null) {
((HeaderViewGridAdapter) adapter).notifyDataSetChanged();
}
}
/**
* For each DragSortListView Listener interface implemented by
* <code>adapter</code>, this method calls the appropriate
* set*Listener method with <code>adapter</code> as the argument.
*
* @param adapter The ListAdapter providing data to back
* DragSortListView.
*
* @see android.widget.ListView#setAdapter(android.widget.ListAdapter)
*/
@Override
public void setAdapter(ListAdapter adapter) {
if (adapter != null) {
mAdapterWrapper = new AdapterWrapper(adapter);
adapter.registerDataSetObserver(mObserver);
if (adapter instanceof DropListener) {
setDropListener((DropListener) adapter);
}
if (adapter instanceof DragListener) {
setDragListener((DragListener) adapter);
}
if (adapter instanceof RemoveListener) {
setRemoveListener((RemoveListener) adapter);
}
} else {
mAdapterWrapper = null;
}
super.setAdapter(mAdapterWrapper);
}
int findCurrentSectionPosition(int fromPosition) {
ListAdapter adapter = getAdapter();
if (adapter instanceof SectionIndexer) {
// try fast way by asking section indexer
SectionIndexer indexer = (SectionIndexer) adapter;
int sectionPosition = indexer.getSectionForPosition(fromPosition);
int itemPosition = indexer.getPositionForSection(sectionPosition);
int typeView = adapter.getItemViewType(itemPosition);
if (isItemViewTypePinned(adapter, typeView)) {
return itemPosition;
} // else, no luck
}
// try slow way by looking through to the next section item above
for (int position=fromPosition; position>=0; position--) {
int viewType = adapter.getItemViewType(position);
if (isItemViewTypePinned(adapter, viewType)) return position;
}
return -1; // no candidate found
}
/**
* @throws java.lang.IllegalStateException if the adapter does not have stable ids.
* @throws java.lang.IllegalArgumentException if the adapter does not implement {@link com.nhaarman.listviewanimations.util.Swappable}.
*/
private void setAdapterInternal(@NonNull final ListAdapter adapter) {
ListAdapter actualAdapter = adapter;
if (actualAdapter instanceof WrapperListAdapter) {
actualAdapter = ((WrapperListAdapter) actualAdapter).getWrappedAdapter();
}
if (!actualAdapter.hasStableIds()) {
throw new IllegalStateException("Adapter doesn't have stable ids! Make sure your adapter has stable ids, and override hasStableIds() to return true.");
}
if (!(actualAdapter instanceof Swappable)) {
throw new IllegalArgumentException("Adapter should implement Swappable!");
}
mAdapter = actualAdapter;
}
/**
* Build adapter, attach to data service, get appropriate cursor, and reset the list.
*
* Cleanup in onDestroyView.
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.v(LOG_TAG, ".onActivityCreated");
super.onActivityCreated(savedInstanceState);
ListAdapter adapter = buildListAdapter();
setListAdapter(adapter);
Activity a = getActivity();
try {
KADataService dataService = ((KADataService.Provider) a).getDataService();
this.call(dataService);
Log.d(LOG_TAG, "Service already available.");
} catch (ServiceUnavailableException e) {
boolean serviceExpected = ((KADataService.Provider) a).requestDataService(this);
Log.d(LOG_TAG, String.format("Service expected: %b.", serviceExpected));
}
getListView().setOverScrollMode(ListView.OVER_SCROLL_ALWAYS);
}
/**
* 对ListView进行截图
* http://stackoverflow.com/questions/12742343/android-get-screenshot-of-all-listview-items
*/
public static Bitmap shotListView(ListView listview) {
ListAdapter adapter = listview.getAdapter();
int itemscount = adapter.getCount();
int allitemsheight = 0;
List<Bitmap> bmps = new ArrayList<Bitmap>();
for (int i = 0; i < itemscount; i++) {
View childView = adapter.getView(i, null, listview);
childView.measure(
View.MeasureSpec.makeMeasureSpec(listview.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());
childView.setDrawingCacheEnabled(true);
childView.buildDrawingCache();
bmps.add(childView.getDrawingCache());
allitemsheight += childView.getMeasuredHeight();
}
Bitmap bigbitmap =
Bitmap.createBitmap(listview.getMeasuredWidth(), allitemsheight, Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bigbitmap);
Paint paint = new Paint();
int iHeight = 0;
for (int i = 0; i < bmps.size(); i++) {
Bitmap bmp = bmps.get(i);
bigcanvas.drawBitmap(bmp, 0, iHeight, paint);
iHeight += bmp.getHeight();
bmp.recycle();
bmp = null;
}
return bigbitmap;
}
public HeaderFooterViewGridAdapter(ArrayList<FixedViewInfo> headerViewInfos, ArrayList<FixedViewInfo> footerViewInfos, ListAdapter adapter) {
mAdapter = adapter;
mIsFilterable = adapter instanceof Filterable;
if (headerViewInfos == null) {
throw new IllegalArgumentException("headerViewInfos cannot be null");
}
if (footerViewInfos == null) {
throw new IllegalArgumentException("footerViewInfos cannot be null");
}
mHeaderViewInfos = headerViewInfos;
mFooterViewInfos = footerViewInfos;
mAreAllFixedViewsSelectable = (areAllListInfosSelectable(mHeaderViewInfos) && areAllListInfosSelectable(mFooterViewInfos));
}
public boolean removeHeaderView(View v) {
if (mHeaderViewInfos.size() > 0) {
boolean result = false;
ListAdapter adapter = getAdapter();
if (adapter != null && adapter instanceof HeaderViewGridAdapter && ((HeaderViewGridAdapter) adapter).removeHeader(v)) {
result = true;
}
removeFixedViewInfo(v, mHeaderViewInfos);
return result;
}
return false;
}
/**
* 获得 ListView 的高度,每一项的高度之和
*/
public static int getListViewHeight(@NonNull ListView listView) {
int totalHeight = 0;
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
}
return totalHeight;
}
/**
* Perform an item click operation on the specified list adapter position.
*
* @param position Adapter position for performing the click
* @return true if the click action could be performed, false if not.
* (e.g. if the popup was not showing, this method would return false.)
*/
public boolean performItemClick(int position) {
if (isShowing()) {
if (mItemClickListener != null) {
final DropDownListView list = mDropDownList;
final View child = list.getChildAt(position - list.getFirstVisiblePosition());
final ListAdapter adapter = list.getAdapter();
mItemClickListener.onItemClick(list, child, position, adapter.getItemId(position));
}
return true;
}
return false;
}
/**
* Find a position that can be selected (i.e., is not a separator).
*
* @param position
* The starting position to look at.
* @param lookDown
* Whether to look down for other positions.
* @return The next selectable position starting at position and then searching either up or down. Returns
* {@link #INVALID_POSITION} if nothing can be found.
*/
@Override
protected int lookForSelectablePosition( int position, boolean lookDown ) {
final ListAdapter adapter = mAdapter;
if ( adapter == null || isInTouchMode() ) {
return INVALID_POSITION;
}
final int count = adapter.getCount();
if ( !mAreAllItemsSelectable ) {
if ( lookDown ) {
position = Math.max( 0, position );
while ( position < count && !adapter.isEnabled( position ) ) {
position++;
}
} else {
position = Math.min( position, count - 1 );
while ( position >= 0 && !adapter.isEnabled( position ) ) {
position--;
}
}
if ( position < 0 || position >= count ) {
return INVALID_POSITION;
}
return position;
} else {
if ( position < 0 || position >= count ) {
return INVALID_POSITION;
}
return position;
}
}
final int[] measureWithLargeChildren(int heightMeasureSpec, int startPosition, int endPosition, int maxWidth, int maxHeight, int disallowPartialChildPosition) {
ListAdapter adapter = this.mAdapter;
if (adapter == null) {
return new int[]{this.mListPadding.left + this.mListPadding.right, this.mListPadding.top + this.mListPadding.bottom};
}
int returnedWidth = this.mListPadding.left + this.mListPadding.right;
int returnedHeight = this.mListPadding.top + this.mListPadding.bottom;
int dividerWidth = (this.mDividerWidth <= 0 || this.mDivider == null) ? 0 : this.mDividerWidth;
int childWidth = 0;
int childHeight = 0;
if (endPosition == -1) {
endPosition = adapter.getCount() - 1;
}
RecycleBin recycleBin = this.mRecycler;
boolean recyle = recycleOnMeasure();
boolean[] isScrap = this.mIsScrap;
for (int i = startPosition; i <= endPosition; i++) {
View child = obtainView(i, isScrap);
measureScrapChildWidth(child, i, heightMeasureSpec);
if (recyle && recycleBin.shouldRecycleViewType(((LayoutParams) child.getLayoutParams()).viewType)) {
recycleBin.addScrapView(child, -1);
}
childWidth = Math.max(childWidth, child.getMeasuredWidth() + dividerWidth);
childHeight = Math.max(childHeight, child.getMeasuredHeight());
}
returnedHeight += childHeight;
return new int[]{Math.min(returnedWidth + childWidth, maxWidth), Math.min(returnedHeight, maxHeight)};
}
@Override
public void setAdapter(ListAdapter adapter) {
mEndlessAdapter = new EndlessAdapter(getContext(), adapter);
mEndlessAdapter.setFooterView(mFooter);
mEndlessAdapter.setFooterStateChangeListener(this);
super.setAdapter(mEndlessAdapter);
}
/**
* As opposed to {@link android.widget.ListView#getAdapter()}, which returns
* a heavily wrapped ListAdapter (DragSortListView wraps the
* input ListAdapter {\emph and} ListView wraps the wrapped one).
*
* @return The ListAdapter set as the argument of {@link setAdapter()}
*/
public ListAdapter getInputAdapter() {
if (mAdapterWrapper == null) {
return null;
} else {
return mAdapterWrapper.getAdapter();
}
}
@Override
public void setAdapter(ListAdapter adapter) {
if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
resetList();
mRecycler.clear();
if (mHeaderViewInfos.size() > 0 || mFooterViewInfos.size() > 0) {
mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
} else {
mAdapter = adapter;
}
// AbsListView#setAdapter will update choice mode states.
super.setAdapter(adapter);
if (mAdapter != null) {
mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
mOldItemCount = mItemCount;
mItemCount = mAdapter.getCount();
checkFocus();
mDataSetObserver = new AdapterDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
} else {
mAreAllItemsSelectable = true;
checkFocus();
}
requestLayout();
}
void recreatePinnedShadow() {
destroyPinnedShadow();
ListAdapter adapter = getAdapter();
if (adapter != null && adapter.getCount() > 0) {
int firstVisiblePosition = getFirstVisiblePosition();
int sectionPosition = findCurrentSectionPosition(firstVisiblePosition);
if (sectionPosition == -1) return; // no views to pin, exit
ensureShadowForPosition(sectionPosition,
firstVisiblePosition, getLastVisiblePosition() - firstVisiblePosition);
}
}
void recreatePinnedShadow() {
destroyPinnedShadow();
ListAdapter adapter = getAdapter();
if (adapter != null && adapter.getCount() > 0) {
int firstVisiblePosition = getFirstVisiblePosition();
int sectionPosition = findCurrentSectionPosition(firstVisiblePosition);
if (sectionPosition == -1) return; // no views to pin, exit
ensureShadowForPosition(sectionPosition,
firstVisiblePosition, getLastVisiblePosition() - firstVisiblePosition);
}
}
protected void setRefreshingInternal(boolean doScroll) {
ListAdapter adapter = ((ExpandableListView) this.mRefreshableView).getAdapter();
if (adapter == null || adapter.isEmpty()) {
super.setRefreshingInternal(doScroll);
return;
}
PullToRefreshHeaderView originalLoadingLayout;
PullToRefreshHeaderView listViewLoadingLayout;
int selection;
int scrollToY;
super.setRefreshingInternal(false);
switch (getCurrentMode()) {
case 2:
originalLoadingLayout = getFooterLayout();
listViewLoadingLayout = this.mFooterLoadingView;
selection = ((ExpandableListView) this.mRefreshableView).getCount() - 1;
scrollToY = getScrollY() - getHeaderHeight();
break;
default:
originalLoadingLayout = getHeaderLayout();
listViewLoadingLayout = this.mHeaderLoadingView;
selection = 0;
scrollToY = getScrollY() + getHeaderHeight();
break;
}
if (doScroll) {
setHeaderScroll(scrollToY);
}
originalLoadingLayout.setVisibility(4);
listViewLoadingLayout.setParams(this.objs);
listViewLoadingLayout.setVisibility(0);
listViewLoadingLayout.refreshing();
if (doScroll) {
((ExpandableListView) this.mRefreshableView).setSelection(selection);
smoothScrollTo(0);
}
}
protected void setRefreshingInternal(boolean doScroll) {
ListAdapter adapter = ((ListView) this.mRefreshableView).getAdapter();
if (adapter == null || adapter.isEmpty()) {
super.setRefreshingInternal(doScroll);
return;
}
PullToRefreshHeaderView originalLoadingLayout;
PullToRefreshHeaderView listViewLoadingLayout;
int selection;
int scrollToY;
super.setRefreshingInternal(false);
switch (getCurrentMode()) {
case 2:
originalLoadingLayout = getFooterLayout();
listViewLoadingLayout = this.mFooterLoadingView;
selection = ((ListView) this.mRefreshableView).getCount() - 1;
scrollToY = getScrollY() - getHeaderHeight();
break;
default:
originalLoadingLayout = getHeaderLayout();
listViewLoadingLayout = this.mHeaderLoadingView;
selection = 0;
scrollToY = getScrollY() + getHeaderHeight();
break;
}
if (doScroll) {
setHeaderScroll(scrollToY);
}
originalLoadingLayout.setVisibility(4);
listViewLoadingLayout.setVisibility(0);
listViewLoadingLayout.setParams(this.objs);
listViewLoadingLayout.refreshing();
if (doScroll) {
((ListView) this.mRefreshableView).setSelection(selection);
smoothScrollTo(0);
}
}