如何在Sectioned Adapter(Android)中获得位置?

时间:2016-07-02 11:17:29

标签: android

我在项目中导入了here中的代码,用于在我的Recycler View中获取带有标题视图的分段适配器。现在我不确定如何在方法onBindItemViewHolder()

中找到位置

这是我的适配器:

public class NotificationHeaderListAdapter extends SectionedAdapter<Notification> {

// Allows to remember the last item shown on screen
private int lastPosition = -1;

private Context mContext;

public NotificationHeaderListAdapter(Context context, List<Notification> notifications) {
    this.mContext = context;
    this.setItemList(notifications);
    this.setCustomHeaderLayout(R.layout.recycler_header_notification);
}

@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, Notification item, @ViewType int viewType) {
    NotificationHolder notificationHolder = (NotificationHolder) holder;

    notificationHolder.tvNotification.setText(
              item.getNotification() + " ti je poslao zahtev za clanstvo u ekipu "
            + item.getGroupName());
    long timestamp = DateUtil.getDifference(item.getTimestamp());
    // Converting timestamp into x ago format
    CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
            Long.parseLong(String.valueOf(timestamp)),
            System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
    notificationHolder.tvTimestamp.setText(timeAgo);

   // Here i need to call my background view for setting animation to list, but i need position for that method
   // setAnimation(notificationHolder.mRelativeLayout, position) ???
}

@Override
public RecyclerView.ViewHolder onCreateItemViewHolder(ViewGroup parent, @ViewType int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.notification_list_item, parent, false);

    return new NotificationHolder(view);
}

public static class NotificationHolder extends RecyclerView.ViewHolder {
    MyTextView tvTimestamp;
    MySecondTextView tvNotification;
    RelativeLayout mRelativeLayout;

    public NotificationHolder(View view) {
        super(view);
        tvTimestamp      = (MyTextView) view.findViewById(R.id.tv_timestamp);
        tvNotification   = (MySecondTextView) view.findViewById(R.id.tv_notification);
        mRelativeLayout  = (RelativeLayout) view.findViewById(R.id.relativeLayout);
    }
}

/**
 * Here is the key method to apply the animation
 */
private void setAnimation(View viewToAnimate, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
        Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
        viewToAnimate.startAnimation(animation);
        lastPosition = position;
    }
}

}

我需要在列表中获取行的位置,因此我可以调用需要两个参数的方法setAnimation()。一个用于传递视图,我设置动画,第二个用于行的位置,但我没有位置。

1 个答案:

答案 0 :(得分:1)

使用holder.getAdapterPosition可以获得行位置

@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, Notification item, @ViewType int viewType) {
  ...
  int position = holder.getAdapterPosition();
  ...
}