#android #listview #adapter
У меня есть активити, в нём один recyclerview адаптер. Как всё переделать в StickyListHeaders как в примере на ресурсе? вот мой адаптер: public class DirectoryAdapter extends RecyclerView.Adapter{ private static int MODE_DIRECTORY = 0; private static int MODE_FAVORITES = 1; public boolean colorTitleStation = true; public interface Listener { void onStationClicked(final Station station); } private final List stations = new LinkedList<>(); private Listener listener; private int mode; public DirectoryAdapter() { stations.addAll(getStations()); } @Override public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { final LayoutInflater inflater = LayoutInflater.from(parent.getContext()); final View view = inflater.inflate(R.layout.directory_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { final Station station = stations.get(position); holder.nameView.setText(station.getName()); holder.genre.setText(String.format("Жанр: %s", station.getNetwork())); holder.descriptionView.setText(String.format("%s", station.getDescription())); Picasso.with(holder.itemView.getContext()).load(station.getIconUrl()).fit().centerCrop().transform(new Transformation() { @Override public Bitmap transform(final Bitmap source) { PaletteCache.generate(station.getIconUrl(), source); return source; } @Override public String key() { return station.getIconUrl(); } }).into(holder.iconView, new Callback() { @Override public void onSuccess() { final Palette palette = PaletteCache.get(station.getIconUrl()); if (palette == null) return; final Palette.Swatch swatch = palette.getVibrantSwatch(); if (swatch != null) { } // ставим цвет заголовка названия станций if (!colorTitleStation){ if (swatch != null) { holder.nameView.setTextColor(swatch.getRgb()); colorTitleStation = false; } } else { colorTitleStation = true; } } @Override public void onError() { } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (listener != null) listener.onStationClicked(station); } }); } @Override public long getItemId(final int position) { return position; } @Override public int getItemCount() { return stations.size(); } private List getStations() { if (mode == MODE_FAVORITES) { return Favorites.getFavorites(); } return Directory.getStations(); } public void showFavorites() { mode = MODE_FAVORITES; updateStations(); } public int showDirectory() {return stations.size();} public void setListener(final Listener listener) { this.listener = listener; } public void filterStations(final String query) { List filteredStations = queryStations(query); updateStations(filteredStations); } public void updateStations(final List filteredStations) { removeFilteredStations(filteredStations); addFilteredStations(filteredStations); } public void updateStations() { updateStations(getStations()); } private void removeFilteredStations(final List filteredStations) { final Iterator iterator = stations.iterator(); while (iterator.hasNext()) { final Station station = iterator.next(); if (!filteredStations.contains(station)) { final int position = stations.indexOf(station); iterator.remove(); notifyItemRemoved(position); } } } private void addFilteredStations(final List filteredStations) { for (Station station : filteredStations) { if (!stations.contains(station)) { final int position = findPosition(station); stations.add(position, station); notifyItemInserted(position); } } } private int findPosition(final Station station) { int position = 0; while(position < stations.size() && stations.get(position).getName().compareToIgnoreCase(station.getName()) < 0) { position++; } return position; } private List queryStations(final String query) { final List filtered = new ArrayList<>(); final boolean isEmpty = TextUtils.isEmpty(query); for (Station station : getStations()) { if (isEmpty || station.matchesQuery(query)) filtered.add(station); } return filtered; } public static class ViewHolder extends RecyclerView.ViewHolder { ImageView iconView; TextView nameView, descriptionView, genre; public ViewHolder(final View itemView) { super(itemView); iconView = (ImageView)itemView.findViewById(R.id.icon); nameView = (TextView)itemView.findViewById(R.id.name); descriptionView = (TextView)itemView.findViewById(R.id.description); genre = (TextView)itemView.findViewById(R.id.genre); } } } вот код из активити с нужным мне "адаптером" как я понял: public class ExpandableListTestActivity extends Activity { private ExpandableStickyListHeadersListView mListView; TestBaseAdapter mTestBaseAdapter; WeakHashMap mOriginalViewHeightPool = new WeakHashMap (); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.expandable_sample); mListView = (ExpandableStickyListHeadersListView) findViewById(R.id.list); //custom expand/collapse animation mListView.setAnimExecutor(new AnimationExecutor()); mTestBaseAdapter = new TestBaseAdapter(this); mListView.setAdapter(mTestBaseAdapter); mListView.setOnHeaderClickListener(new StickyListHeadersListView.OnHeaderClickListener() { @Override public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId, boolean currentlySticky) { if(mListView.isHeaderCollapsed(headerId)){ mListView.expand(headerId); }else { mListView.collapse(headerId); } } }); } //animation executor class AnimationExecutor implements ExpandableStickyListHeadersListView.IAnimationExecutor { @Override public void executeAnim(final View target, final int animType) { if(ExpandableStickyListHeadersListView.ANIMATION_EXPAND==animType&&target.getVisibility()==View.VISIBLE){ return; } if(ExpandableStickyListHeadersListView.ANIMATION_COLLAPSE==animType&&target.getVisibility()!=View.VISIBLE){ return; } if(mOriginalViewHeightPool.get(target)==null){ mOriginalViewHeightPool.put(target,target.getHeight()); } final int viewHeight = mOriginalViewHeightPool.get(target); float animStartY = animType == ExpandableStickyListHeadersListView.ANIMATION_EXPAND ? 0f : viewHeight; float animEndY = animType == ExpandableStickyListHeadersListView.ANIMATION_EXPAND ? viewHeight : 0f; final ViewGroup.LayoutParams lp = target.getLayoutParams(); ValueAnimator animator = ValueAnimator.ofFloat(animStartY, animEndY); animator.setDuration(200); target.setVisibility(View.VISIBLE); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { if (animType == ExpandableStickyListHeadersListView.ANIMATION_EXPAND) { target.setVisibility(View.VISIBLE); } else { target.setVisibility(View.GONE); } target.getLayoutParams().height = viewHeight; } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { lp.height = ((Float) valueAnimator.getAnimatedValue()).intValue(); target.setLayoutParams(lp); target.requestLayout(); } }); animator.start(); } } } не совсем пойму, как и что заменить для того чтоб мой список listview был как в примере... Заранее спасибо!
Ответы
Ответ 1
Собственно, нужно переделать адаптер таким образом, чтобы он наследовал BaseAdapter и отвечал интерфейсу StickyListHeadersAdapter. Как-то так: public class NewDirectoryAdapter extends BaseAdapter implements StickyListHeadersAdapter { private static int MODE_DIRECTORY = 0; private static int MODE_FAVORITES = 1; public boolean colorTitleStation = true; public interface Listener { void onStationClicked(final Station station); } private final Liststations = new LinkedList<>(); private Listener listener; private int mode; public NewDirectoryAdapter() { stations.addAll(getStations()); } @Override public View getHeaderView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; if (convertView == null) { holder = new HeaderViewHolder(); convertView = LayoutInflater.from(parent.getContext()) .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 = "" + getItem(position).getName().subSequence(0, 1).charAt(0); holder.text.setText(headerText); return convertView; } @Override public long getHeaderId(int position) { return getItem(position).getName().subSequence(0, 1).charAt(0); } @Override public int getCount() { return stations.size(); } @Override public Station getItem(int position) { return stations.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.directory_item, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } final Station station = stations.get(position); holder.nameView.setText(station.getName()); holder.genre.setText(String.format("Жанр: %s", station.getNetwork())); holder.descriptionView.setText(String.format("%s", station.getDescription())); Picasso.with(holder.itemView.getContext()).load(station.getIconUrl()).fit().centerCrop().transform(new Transformation() { @Override public Bitmap transform(final Bitmap source) { PaletteCache.generate(station.getIconUrl(), source); return source; } @Override public String key() { return station.getIconUrl(); } }).into(holder.iconView, new Callback() { @Override public void onSuccess() { final Palette palette = PaletteCache.get(station.getIconUrl()); if (palette == null) return; final Palette.Swatch swatch = palette.getVibrantSwatch(); if (swatch != null) { } // ставим цвет заголовка названия станций if (!colorTitleStation){ if (swatch != null) { holder.nameView.setTextColor(swatch.getRgb()); colorTitleStation = false; } } else { colorTitleStation = true; } } @Override public void onError() { } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (listener != null) listener.onStationClicked(station); } }); } private List getStations() { if (mode == MODE_FAVORITES) { return Favorites.getFavorites(); } return Directory.getStations(); } public void showFavorites() { mode = MODE_FAVORITES; updateStations(); } public int showDirectory() {return stations.size();} public void setListener(final Listener listener) { this.listener = listener; } public void filterStations(final String query) { List filteredStations = queryStations(query); updateStations(filteredStations); } public void updateStations(final List filteredStations) { removeFilteredStations(filteredStations); addFilteredStations(filteredStations); } public void updateStations() { updateStations(getStations()); } private void removeFilteredStations(final List filteredStations) { final Iterator iterator = stations.iterator(); while (iterator.hasNext()) { final Station station = iterator.next(); if (!filteredStations.contains(station)) { final int position = stations.indexOf(station); iterator.remove(); notifyItemRemoved(position); } } } private void addFilteredStations(final List filteredStations) { for (Station station : filteredStations) { if (!stations.contains(station)) { final int position = findPosition(station); stations.add(position, station); notifyItemInserted(position); } } } private int findPosition(final Station station) { int position = 0; while(position < stations.size() && stations.get(position).getName().compareToIgnoreCase(station.getName()) < 0) { position++; } return position; } private List queryStations(final String query) { final List filtered = new ArrayList<>(); final boolean isEmpty = TextUtils.isEmpty(query); for (Station station : getStations()) { if (isEmpty || station.matchesQuery(query)) filtered.add(station); } return filtered; } public static class ViewHolder { View itemView; ImageView iconView; TextView nameView, descriptionView, genre; public ViewHolder(final View itemView) { this.itemView = itemView; iconView = (ImageView)itemView.findViewById(R.id.icon); nameView = (TextView)itemView.findViewById(R.id.name); descriptionView = (TextView)itemView.findViewById(R.id.description); genre = (TextView)itemView.findViewById(R.id.genre); } } public static class HeaderViewHolder { private TextView text; } } Далее в качестве списка можно использовать StickyListHeadersListView (в примере он) вместо ExpandableStickyListHeadersListView (аналог, позволяющий раскрывать элементы списка). Соответственно, код ExpandableListTestActivity может выглядеть как-то так: public class ExpandableListTestActivity extends Activity { private ExpandableStickyListHeadersListView mListView; TestBaseAdapter mTestBaseAdapter; WeakHashMap mOriginalViewHeightPool = new WeakHashMap (); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.expandable_sample); mListView = (ExpandableStickyListHeadersListView) findViewById(R.id.list); //custom expand/collapse animation mListView.setAnimExecutor(new AnimationExecutor()); mTestBaseAdapter = new TestBaseAdapter(this); mListView.setAdapter(mTestBaseAdapter); } }
Комментариев нет:
Отправить комментарий