2016-05-11 4 views
-1

Мое приложение это Интернет-рынок. Я могу добавить товар в корзину. Я пытаюсь изменить значок из «добавить в корзину» на «в корзину». Но это работает неправильно. Если я добавлю только один продукт и прокручу вниз, изменится иконка других продуктов. В адаптере RecyclerView OnBindViewHolder я использую условие , если.Условия использования IF в RecyclerView

if (getTableBasket().contains(p.getId())) 
    prudactViewHolder.btn_buy.setBackgroundResource(R.drawable.tool); 
else 
    prudactViewHolder.btn_buy.setBackgroundResource(R.drawable.tool1); 

.... 

ArrayList<Integer> getTableBasket(){ 

     ArrayList<Integer> id_list = new ArrayList<>(); 
     dbHelper = new DBHelper(mContext); 
     SQLiteDatabase db = dbHelper.getWritableDatabase(); 
     Cursor c = db.query("basket", null, null, null, null, null, null); 
     if (c.moveToFirst()) { 
      int id_prudactColIndex = c.getColumnIndex("id_prudact"); 
      do { 
       id_list.add(c.getInt(id_prudactColIndex)); 

      } while (c.moveToNext()); 
     } else 
      Log.d(LOG_TAG, "In basket 0 rows"); 
     c.close(); 

     return id_list; 
    } 

EDIT Хорошо, я получить данные от сервера в формате JSON. И отобразите его в recyclerview. Я могу добавить прудакт в корзину, для этого я создаю таблицу «Букет». Когда пользователь добавляет товар в корзину, данные pudact добавляются в «Букет». И, например, пользователь закрывает приложение. И снова вернемся к приложению, он может найти, что его добавленный продукт в другой значок и не добавил продукт в другой значок.

моя дб структура

db.execSQL("create table basket (" 
       + "id integer primary key autoincrement," 
       + "id_prudact integer," 
       + "name text," 
       + "id_image integer," 
       + "count integer," 
       + "price integer," 
       + "priceOld integer," 
       + "nomer_zakaz text" + ");"); 

     db.execSQL("create table favorite (" 
       + "id integer primary key autoincrement," 
       + "id_prudact integer," 
       + "name text," 
       + "id_image text," 
       + "count integer," 
       + "price integer," 
       + "priceOld integer" + ");"); 

Мой Полный адаптер.

public class PrudactAdapter extends RecyclerView.Adapter<PrudactAdapter.PrudactViewHolder> { 

    List<PrudactModel> prudactsList; 
    public Context mContext; 
    public static EditPlayerAdapterCallback callback; 
    ArrayList<PrudactBusketModel> busketList = new ArrayList<>(); 
    DBHelper dbHelper; 
    ImageLoader imageLoader = AppController.getInstance().getImageLoader(); 
    public ArrayList<Integer> tableBasket = new ArrayList<Integer>(); 
    public ArrayList<Integer> tableFavorite = new ArrayList<>(); 
    String LOG_TAG = "myLogs"; 

    public PrudactAdapter(List<PrudactModel> persons, Context context){ 
     this.prudactsList = persons; 
     this.mContext = context; 


    } 

    @Override 
    public PrudactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_of_pruduct, parent, false); 
     PrudactViewHolder pvh = new PrudactViewHolder(v,mContext); 

     return pvh; 
    } 


    @Override 
    public int getItemViewType(int position) { 
     return super.getItemViewType(position); 


    } 

    @Override 
    public void onBindViewHolder(final PrudactViewHolder prudactViewHolder, final int i) { 

     if (imageLoader == null) 
      imageLoader = AppController.getInstance().getImageLoader(); 

     final PrudactModel p = prudactsList.get(i); 
     prudactViewHolder.catalogName.setText(p.getName()); 
     prudactViewHolder.catalogPrice.setText(Integer.toString(p.getPrice())+" тг"); 
     prudactViewHolder.catalogPriceOld.setText(Integer.toString(p.getOldPrice())+" тг"); 
     prudactViewHolder.thumbNail.setImageUrl(p.getImgId(),imageLoader); 
     // final MediaPlayer addSound = MediaPlayer.create(mContext,R.raw.button28); 
     //// TODO Cheking PRICE 

     if (p.getOldPrice()==0){ 
      prudactViewHolder.catalogPriceOld.setVisibility(View.INVISIBLE); 
      prudactViewHolder.aksia.setVisibility(View.INVISIBLE); 
      prudactViewHolder.catalogPrice.setTextColor(ContextCompat.getColor(mContext, R.color.black)); 
     } 
     else { 
      prudactViewHolder.catalogPrice.setTextColor(ContextCompat.getColor(mContext, R.color.red)); 
      prudactViewHolder.catalogPriceOld.setVisibility(View.VISIBLE); 
      prudactViewHolder.aksia.setVisibility(View.VISIBLE); 
     } 

     //// TODO Cheking DB 

     if (getTableBasket().contains(p.getId())) 
      prudactViewHolder.btn_buy.setBackgroundResource(R.drawable.tool); 
     else 
      prudactViewHolder.btn_buy.setBackgroundResource(R.drawable.tool1); 

     if (getTableFavorite().contains(p.getId())) 
      prudactViewHolder.btn_favorite.setBackgroundResource(R.drawable.favorite_d); 
     else 
      prudactViewHolder.btn_favorite.setBackgroundResource(R.drawable.favorite_c); 

     //// TODO: 02.05.2016 BUY BUTTON CLICK 

     prudactViewHolder.ll_buy.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       dbHelper = new DBHelper(mContext); 
       final ContentValues cv = new ContentValues(); 
       final SQLiteDatabase db = dbHelper.getWritableDatabase(); 
       if (prudactViewHolder.btn_buy.getBackground().getConstantState()== ContextCompat.getDrawable(mContext,R.drawable.tool1).getConstantState()){ 
        updateBuyButton(prudactViewHolder, true); 
        Log.d(LOG_TAG, "--- Insert in mytable: ---"); 
        cv.put("id_prudact", p.getId()); 
        cv.put("name",p.getName()); 
        cv.put("id_image",p.getImgId()); 
        cv.put("count",1); 
        cv.put("price",p.getPrice()); 
        cv.put("priceOld",p.getOldPrice()); 
        long rowID = db.insert("basket", null, cv); 
        Log.d(LOG_TAG, "row to basket inserted, ID = " + rowID); 
        callback.folderClicked(1); 
       } 
       else { 
        updateBuyButton2(prudactViewHolder, true); 
        callback.folderClicked(-1); 
        db.delete("basket","id_prudact=?",new String[]{String.valueOf(p.getId())}); 
       } 
       dbHelper.close(); 
      } 
     }); 

     prudactViewHolder.btn_buy.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       dbHelper = new DBHelper(mContext); 
       final ContentValues cv = new ContentValues(); 
       final SQLiteDatabase db = dbHelper.getWritableDatabase(); 
       if (prudactViewHolder.btn_buy.getBackground().getConstantState()== ContextCompat.getDrawable(mContext,R.drawable.tool1).getConstantState()){ 
        updateBuyButton(prudactViewHolder, true); 
        Log.d(LOG_TAG, "--- Insert in mytable: ---"); 
        cv.put("id_prudact", p.getId()); 
        cv.put("name",p.getName()); 
        cv.put("id_image",p.getImgId()); 
        cv.put("count",1); 
        cv.put("price",p.getPrice()); 
        cv.put("priceOld",p.getOldPrice()); 
        long rowID = db.insert("basket", null, cv); 
        Log.d(LOG_TAG, "row to basket inserted, ID = " + rowID); 
        callback.folderClicked(1); 
       } 
       else { 
        updateBuyButton2(prudactViewHolder, true); 
        callback.folderClicked(-1); 
        db.delete("basket","id_prudact=?",new String[]{String.valueOf(p.getId())}); 
       } 
       dbHelper.close(); 
      } 
     }); 

     //// TODO: 02.05.2016 FAVORITE BUTTON CLICK 

     prudactViewHolder.ll_favorite.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       dbHelper = new DBHelper(mContext); 
       final ContentValues cv = new ContentValues(); 
       final SQLiteDatabase db = dbHelper.getWritableDatabase(); 
       if (prudactViewHolder.btn_favorite.getBackground().getConstantState()== ContextCompat.getDrawable(mContext,R.drawable.favorite_c).getConstantState()){ 
        updateHeartButton(prudactViewHolder, true); 
        cv.put("id_prudact", p.getId()); 
        cv.put("name",p.getName()); 
        cv.put("id_image",p.getImgId()); 
        cv.put("count",1); 
        cv.put("price",p.getPrice()); 
        cv.put("priceOld",p.getOldPrice()); 
        long rowID = db.insert("favorite", null, cv); 
        Log.d(LOG_TAG, "row to favorite inserted, ID = " + rowID); 
       } 

       else { 
        updateHeartButton2(prudactViewHolder, true); 
        db.delete("favorite","id_prudact=?",new String[]{String.valueOf(p.getId())}); 
       } 
      } 
     }); 

     prudactViewHolder.btn_favorite.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       dbHelper = new DBHelper(mContext); 
       final ContentValues cv = new ContentValues(); 
       final SQLiteDatabase db = dbHelper.getWritableDatabase(); 
       if (prudactViewHolder.btn_favorite.getBackground().getConstantState()== ContextCompat.getDrawable(mContext,R.drawable.favorite_c).getConstantState()){ 
        updateHeartButton(prudactViewHolder, true); 
        cv.put("id_prudact", p.getId()); 
        cv.put("name",p.getName()); 
        cv.put("id_image",p.getImgId()); 
        cv.put("count",1); 
        cv.put("price",p.getPrice()); 
        cv.put("priceOld",p.getOldPrice()); 
        long rowID = db.insert("favorite", null, cv); 
        Log.d(LOG_TAG, "row to favorite inserted, ID = " + rowID); 

       } 
       else { 
        updateHeartButton2(prudactViewHolder, true); 
        db.delete("favorite","id_prudact=?",new String[]{String.valueOf(p.getId())}); 
       } 
      } 
     }); 

     //// TODO: 02.05.2016 SHARE BUTTON CLICK 

     prudactViewHolder.ll_share.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String shareBody = "Мне нравится "+p.getName()+" за "+p.getPrice()+" тенге. unimax.kz"; 
       Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
       sharingIntent.setType("text/plain"); 
       sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here"); 
       sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); 
       mContext.startActivity(Intent.createChooser(sharingIntent,"Elaman")); 
      } 
     }); 
     prudactViewHolder.btn_share.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String shareBody = "Мне нравится "+p.getName()+" за "+p.getPrice()+" тенге. unimax.kz"; 
       Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
       sharingIntent.setType("text/plain"); 
       sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here"); 
       sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); 
       mContext.startActivity(Intent.createChooser(sharingIntent,"Elaman")); 
      } 
     }); 

     prudactViewHolder.thumbNail.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(mContext, ImageActivity.class); 
       intent.putExtra("image",p.getImgId()); 
       mContext.startActivity(intent); 
      } 
     }); 


     dbHelper.close(); 

    } 

    private static final AccelerateInterpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator(); 
    private static final OvershootInterpolator OVERSHOOT_INTERPOLATOR = new OvershootInterpolator(4); 

    private void updateHeartButton(final PrudactViewHolder holder, boolean animated) { 
     if (animated) { 
       AnimatorSet animatorSet = new AnimatorSet(); 

       ObjectAnimator rotationAnim = ObjectAnimator.ofFloat(holder.btn_favorite, "rotation", 0f, 360f); 
       rotationAnim.setDuration(300); 
       rotationAnim.setInterpolator(ACCELERATE_INTERPOLATOR); 

       ObjectAnimator bounceAnimX = ObjectAnimator.ofFloat(holder.btn_favorite, "scaleX", 0.2f, 1f); 
       bounceAnimX.setDuration(300); 
       bounceAnimX.setInterpolator(OVERSHOOT_INTERPOLATOR); 

       ObjectAnimator bounceAnimY = ObjectAnimator.ofFloat(holder.btn_favorite, "scaleY", 0.2f, 1f); 
       bounceAnimY.setDuration(300); 
       bounceAnimY.setInterpolator(OVERSHOOT_INTERPOLATOR); 
       bounceAnimY.addListener(new AnimatorListenerAdapter() { 
        @Override 
        public void onAnimationStart(Animator animation) { 
         holder.btn_favorite.setBackgroundResource(R.drawable.favorite_d); 
        } 
       }); 

       animatorSet.play(rotationAnim); 
       animatorSet.play(bounceAnimX).with(bounceAnimY).after(rotationAnim); 
       animatorSet.start(); 
     } 
    } 

    private void updateHeartButton2(final PrudactViewHolder holder, boolean animated) { 
     if (animated) { 
      AnimatorSet animatorSet = new AnimatorSet(); 

      ObjectAnimator rotationAnim = ObjectAnimator.ofFloat(holder.btn_favorite, "rotation", 0f, 360f); 
      rotationAnim.setDuration(300); 
      rotationAnim.setInterpolator(ACCELERATE_INTERPOLATOR); 

      ObjectAnimator bounceAnimX = ObjectAnimator.ofFloat(holder.btn_favorite, "scaleX", 0.2f, 1f); 
      bounceAnimX.setDuration(300); 
      bounceAnimX.setInterpolator(OVERSHOOT_INTERPOLATOR); 

      ObjectAnimator bounceAnimY = ObjectAnimator.ofFloat(holder.btn_favorite, "scaleY", 0.2f, 1f); 
      bounceAnimY.setDuration(300); 
      bounceAnimY.setInterpolator(OVERSHOOT_INTERPOLATOR); 
      bounceAnimY.addListener(new AnimatorListenerAdapter() { 
       @Override 
       public void onAnimationStart(Animator animation) { 
        holder.btn_favorite.setBackgroundResource(R.drawable.favorite_c); 
       } 
      }); 

      animatorSet.play(rotationAnim); 
      animatorSet.play(bounceAnimX).with(bounceAnimY).after(rotationAnim); 
      animatorSet.start(); 
     } 
    } 

    private void updateBuyButton(final PrudactViewHolder holder, boolean animated) { 
     if (animated) { 
      AnimatorSet animatorSet = new AnimatorSet(); 

      ObjectAnimator rotationAnim = ObjectAnimator.ofFloat(holder.btn_buy, "rotation", 0f, 360f); 
      rotationAnim.setDuration(300); 
      rotationAnim.setInterpolator(ACCELERATE_INTERPOLATOR); 

      ObjectAnimator bounceAnimX = ObjectAnimator.ofFloat(holder.btn_buy, "scaleX", 0.2f, 1f); 
      bounceAnimX.setDuration(300); 
      bounceAnimX.setInterpolator(OVERSHOOT_INTERPOLATOR); 

      ObjectAnimator bounceAnimY = ObjectAnimator.ofFloat(holder.btn_buy, "scaleY", 0.2f, 1f); 
      bounceAnimY.setDuration(300); 
      bounceAnimY.setInterpolator(OVERSHOOT_INTERPOLATOR); 
      bounceAnimY.addListener(new AnimatorListenerAdapter() { 
       @Override 
       public void onAnimationStart(Animator animation) { 
        holder.btn_buy.setBackgroundResource(R.drawable.tool); 
       } 
      }); 

      animatorSet.play(rotationAnim); 
      animatorSet.play(bounceAnimX).with(bounceAnimY).after(rotationAnim); 
      animatorSet.start(); 
     } 
    } 

    private void updateBuyButton2(final PrudactViewHolder holder, boolean animated) { 
     if (animated) { 
      AnimatorSet animatorSet = new AnimatorSet(); 

      ObjectAnimator rotationAnim = ObjectAnimator.ofFloat(holder.btn_buy, "rotation", 0f, 360f); 
      rotationAnim.setDuration(300); 
      rotationAnim.setInterpolator(ACCELERATE_INTERPOLATOR); 

      ObjectAnimator bounceAnimX = ObjectAnimator.ofFloat(holder.btn_buy, "scaleX", 0.2f, 1f); 
      bounceAnimX.setDuration(300); 
      bounceAnimX.setInterpolator(OVERSHOOT_INTERPOLATOR); 

      ObjectAnimator bounceAnimY = ObjectAnimator.ofFloat(holder.btn_buy, "scaleY", 0.2f, 1f); 
      bounceAnimY.setDuration(300); 
      bounceAnimY.setInterpolator(OVERSHOOT_INTERPOLATOR); 
      bounceAnimY.addListener(new AnimatorListenerAdapter() { 
       @Override 
       public void onAnimationStart(Animator animation) { 
        holder.btn_buy.setBackgroundResource(R.drawable.tool1); 
       } 
      }); 

      animatorSet.play(rotationAnim); 
      animatorSet.play(bounceAnimX).with(bounceAnimY).after(rotationAnim); 
      animatorSet.start(); 
     } 
    } 

    @Override 
    public void onAttachedToRecyclerView(RecyclerView recyclerView) { 
     super.onAttachedToRecyclerView(recyclerView); 
    } 

    @Override 
    public int getItemCount() { 
     return prudactsList.size(); 
    } 

    public void setCallback(EditPlayerAdapterCallback callback2){ 

     callback = callback2; 
    } 

    public static class PrudactViewHolder extends RecyclerView.ViewHolder{ 

     CardView cv; 
     TextView catalogName,catalogPrice,catalogPriceOld; 
     NetworkImageView thumbNail; 
     ImageButton btn_favorite,btn_share, btn_buy; 
     LinearLayout ll_buy,aksia,ll_share,ll_favorite; 

     public PrudactViewHolder(View itemView,Context context) { 
      super(itemView); 
      cv = (CardView)itemView.findViewById(R.id.cv); 
      catalogName = (TextView)itemView.findViewById(R.id.name_catalog); 
      catalogPrice = (TextView)itemView.findViewById(R.id.price_catalog); 
      catalogPriceOld = (TextView)itemView.findViewById(R.id.old_price_catalog); 

      btn_buy = (ImageButton) itemView.findViewById(R.id.btn_buy); 
      btn_share = (ImageButton) itemView.findViewById(R.id.btn_share); 
      btn_favorite = (ImageButton) itemView.findViewById(R.id.izbrannyi); 

      thumbNail = (NetworkImageView)itemView.findViewById(R.id.image_catalog); 
      aksia = (LinearLayout) itemView.findViewById(R.id.aksia); 
      ll_buy = (LinearLayout) itemView.findViewById(R.id.ll_buy); 
      ll_share = (LinearLayout) itemView.findViewById(R.id.ll_share); 
      ll_favorite = (LinearLayout) itemView.findViewById(R.id.ll_favorite); 

      catalogPriceOld.setPaintFlags(catalogPriceOld.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG); 

     } 
    } 

    ArrayList<Integer> getTableBasket(){ 

     ArrayList<Integer> id_list = new ArrayList<>(); 
     dbHelper = new DBHelper(mContext); 
     SQLiteDatabase db = dbHelper.getWritableDatabase(); 
     Cursor c = db.query("basket", null, null, null, null, null, null); 
     if (c.moveToFirst()) { 
      int id_prudactColIndex = c.getColumnIndex("id_prudact"); 
      do { 
       id_list.add(c.getInt(id_prudactColIndex)); 

      } while (c.moveToNext()); 
     } else 
      Log.d(LOG_TAG, "In basket 0 rows"); 
     c.close(); 

     return id_list; 
    } 

    ArrayList<Integer> getTableFavorite(){ 

     ArrayList<Integer> id_list = new ArrayList<>(); 
     dbHelper = new DBHelper(mContext); 
     SQLiteDatabase db = dbHelper.getWritableDatabase(); 
     Cursor c = db.query("favorite", null, null, null, null, null, null); 
     if (c.moveToFirst()) { 
      int id_prudactColIndex = c.getColumnIndex("id_prudact"); 
      do { 
       id_list.add(c.getInt(id_prudactColIndex)); 

      } while (c.moveToNext()); 
     } else 
      Log.d(LOG_TAG, "In favorite 0 rows"); 
     c.close(); 

     return id_list; 
    } 
} 

К сожалению, это по-русски my app image

+0

Что такое p.getId? –

+0

@HirenPatel это идентификатор prudact – eluuu

ответ

1

общественного класса AdapterTrashIncome расширяет RecyclerView.Adapter {

private ArrayList<ObjectIncome> myItems = new ArrayList<>(); 

public AdapterTrashIncome(ArrayList<ObjectIncome> getItems, Context context){ 
    try { 
     mContext = context; 
     myItems = getItems; 
     }catch (Exception e){ 
     Log.e(FILE_NAME, "51: " + e.toString()); 
     e.printStackTrace(); 
    } 
} 

public class ViewHolder extends RecyclerView.ViewHolder { 
    public TextView tvContent; 
    public CheckBox cbSelect; 

    public ViewHolder(View v) { 
     super(v); 
     tvContent = (TextView) v.findViewById(R.id.tvContent); 
     cbSelect = (CheckBox) v.findViewById(R.id.cbSelect); 
    } 
} 

@Override 
public void onBindViewHolder(ViewHolder holder, final int position) { 
    final ObjectIncome objIncome = myItems.get(position); 
    String content = "<b>lalalla</b>"; 
    holder.tvContent.setText(Html.fromHtml(content)); 

    //in some cases, it will prevent unwanted situations 
    holder.cbSelect.setOnCheckedChangeListener(null); 

    //if true, your checkbox will be selected, else unselected 
    holder.cbSelect.setChecked(objIncome.isSelected()); 

    holder.cbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       //set your object's last status 
       objIncome.setSelected(isChecked); 
     } 
    }); 

} 

}

1

Лучше вы можете сохранить продукт в корзину или нет в классе модели например:

Product{ boolean isInCart; ..... }

и предоставить этот тип arraylist в адаптере для ресайклеров. то только одно условие:

if (getItem(position).isInCart()) 
prudactViewHolder.btn_buy.setBackgroundResource(R.drawable.tool); 
else 
prudactViewHolder.btn_buy.setBackgroundResource(R.drawable.tool1); 

в противном случае он будет делать forloop по каждому пункту, который плохо для пользовательского интерфейса, а также для памяти.

Если вы все еще не в состоянии получить его озираться по этой ссылке: http://amolsawant88.blogspot.in/2015/08/easy-way-to-highlight-selected-rowitem.html вещь отличается, но он меняется фон вы хотите изменить изображение только контекст отличается, но дело в том же.

+1

Но я получаю данные из БД. Я запутываю – eluuu

+0

Итак, чтобы получить данные из db, все в порядке, но создайте arraylist моделей продуктов так, как вам больше не нужно делать для цикла на каждом продукте. можете ли вы вставить структуру db, тогда я дам лучшее понимание. –

+0

Я отредактировал мой пост – eluuu

0
private static final int PHOTO_ANIMATION_DELAY = 600; 
private static final Interpolator INTERPOLATOR = new DecelerateInterpolator(); 


private final Context context; 
private final int cellSize; 
private final List<String> photos; 
private boolean lockedAnimations = false; 
private int lastAnimatedItem = -1; 

public Adapter_grid_list_profile(Context context) { 
this.context = context; 
this.cellSize = com.elite.watchme.commonFunctionalityController.ScreenUtils.getScreenWidth(context)/3; 
this.photos = Arrays.asList(context.getResources().getStringArray(R.array.user_photos)); 
} 

@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
final View view = LayoutInflater.from(context).inflate(R.layout.item_photo, parent, false); 
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams(); 
layoutParams.height = cellSize; 
layoutParams.width = cellSize; 
layoutParams.setFullSpan(false); 
view.setLayoutParams(layoutParams); 
return new PhotoViewHolder(view); 
} 

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { 
bindPhoto((PhotoViewHolder) holder, position); 
} 

private void bindPhoto(final PhotoViewHolder holder, int position) { 
Picasso.with(context) 
.load(FragmentProfileScreen.imageUrlsHorizontal.get(position)) 
.resize(cellSize, cellSize) 
.centerCrop() 
.into(holder.ivPhoto, new Callback() { 
@Override 
public void onSuccess() { 
animatePhoto(holder); 
} 

@Override 
public void onError() { 

} 
}); 
if (lastAnimatedItem < position) lastAnimatedItem = position; 
} 

private void animatePhoto(PhotoViewHolder viewHolder) { 
if (!lockedAnimations) { 
if (lastAnimatedItem == viewHolder.getPosition()) { 
setLockedAnimations(true); 
} 

long animationDelay = PHOTO_ANIMATION_DELAY + viewHolder.getPosition() * 30; 

viewHolder.flRoot.setScaleY(0); 
viewHolder.flRoot.setScaleX(0); 

viewHolder.flRoot.animate() 
.scaleY(1) 
.scaleX(1) 
.setDuration(200) 
.setInterpolator(INTERPOLATOR) 
.setStartDelay(animationDelay) 
Смежные вопросы