2015-01-23 2 views
2

Я пытаюсь реализовать динамический вид внутри RecyclerView, и у меня возникают проблемы с дублированием отдельных элементов управления.RecyclerView, дублирующий определенные элементы пользовательского интерфейса

Вот мой RecyclerView.ViewHolder

class CardHolder extends RecyclerView.ViewHolder{ 
    private ICard card; 
    private TextView cost; 
    private ImageView quickAction; 
    private TextView range; 
    private TextView life; 
    private TextView defense; 
    private TextView spellName; 
    private ImageView addCard; 
    private TextView maximumCards; 
    private ImageView removeCard; 
    private ImageView cardImage; 
    private LinearLayout cardImageRow; 
    private LinearLayout traitsRow; 
    private TextView effects; 
    private LinearLayout attackColumn; 


    public CardHolder(View itemView) { 
     super(itemView); 

     cost = (TextView)itemView.findViewById(R.id.card_cost); 
     quickAction = (ImageView)itemView.findViewById(R.id.quickAction); 
     range = (TextView)itemView.findViewById(R.id.range); 
     life = (TextView)itemView.findViewById(R.id.life); 
     defense = (TextView)itemView.findViewById(R.id.defense); 
     spellName = (TextView)itemView.findViewById(R.id.spellName); 
     addCard = (ImageView)itemView.findViewById(R.id.addCard); 
     addCard.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

      } 
     }); 
     maximumCards = (TextView)itemView.findViewById(R.id.maximumCards); 
     removeCard = (ImageView)itemView.findViewById(R.id.removeCard); 
     removeCard.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

      } 
     }); 
     cardImage = (ImageView)itemView.findViewById(R.id.cardImage); 
     cardImage.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

      } 
     }); 
     cardImageRow = (LinearLayout)itemView.findViewById(R.id.cardImageRow); 
     traitsRow = (LinearLayout)itemView.findViewById(R.id.traitsRow); 
     effects = (TextView)itemView.findViewById(R.id.effects); 
     attackColumn = (LinearLayout)itemView.findViewById(R.id.attackColumn); 
    } 

    public void setCard(Card card){ 
     this.card = card; 

     cost.setText(card.getCost() + ""); 
     quickAction.setImageResource(card.isQuickAction() ? R.drawable.quickaction : R.drawable.fullaction); 
     range.setText(card.getMinRange() + "-" + card.getMaxRange()); 
     spellName.setText(card.getSpellName()); 
     cardImage.setImageResource(card.getCardImageResourceId()); 
     effects.setText(card.getEffect()); 

     if(card instanceof AttackCard){ 
      AttackCard c = (AttackCard)card; 
      handleAttack(c.getAttack()); 
     } 


     if(card.getTrait() != null){ 
      boolean isFirst = true; 
      StringBuilder builder = new StringBuilder(); 
      for(int i = 0; i < card.getTrait().getAll().size(); i++){ 
       if(isFirst){ 
        builder.append(card.getTrait().get(i).getType().toString()); 
        isFirst = false; 
       } 
       else{ 
        builder.append(" \u2022 "); 
        builder.append(card.getTrait().get(i).getType().toString()); 
       } 
      } 

      TextView t = new TextView(getActivity()); 
      t.setText(builder.toString()); 
      t.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); 
      t.setTextColor(Color.BLACK); 
      t.setTextSize(TypedValue.COMPLEX_UNIT_SP,14); 
      t.setTypeface(Typeface.DEFAULT_BOLD); 
      traitsRow.addView(t); 


     } 
    } 
    private void handleAttack(ICardProperty<IAttack> attack){ 
     if(attack == null){ 
      return; 
     } 

     for(int i = 0; i < attack.getAll().size(); i++) { 

      IAttack a = attack.get(i); 

      //Layout for entire Attack 
      RelativeLayout layout = new RelativeLayout(getActivity()); 
      //layout.setId(Utils.generateViewId()); 
      layout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); 

      //Attack name 
      TextView attackName = new TextView(getActivity()); 
      attackName.setId(Utils.generateViewId()); 
      attackName.setText(a.getName()); 
      attackName.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 
      attackName.setTextColor(Color.BLACK); 
      attackName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); 
      layout.addView(attackName); 


      //Quick action or Full action 
      ImageView quickAction = new ImageView(getActivity()); 
      quickAction.setId(Utils.generateViewId()); 
      RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(R.dimen.card_header_width,R.dimen.card_header_height); 
      lp.addRule(RelativeLayout.BELOW,attackName.getId()); 
      lp.addRule(RelativeLayout.CENTER_VERTICAL); 
      quickAction.setLayoutParams(lp); 
      quickAction.setImageResource(a.isQuickAction() ? R.drawable.quickaction : R.drawable.fullaction); 
      layout.addView(quickAction); 

      //Attack type (Melee or Ranged) 
      TextView attackType = new TextView(getActivity()); 
      attackType.setId(Utils.generateViewId()); 
      attackType.setGravity(Gravity.CENTER); 

      RelativeLayout.LayoutParams p1 = new RelativeLayout.LayoutParams(R.dimen.attack_width,R.dimen.attack_height); 
      p1.addRule(RelativeLayout.RIGHT_OF,quickAction.getId()); 
      p1.addRule(RelativeLayout.BELOW,attackName.getId()); 
      p1.setMargins(2,0,2,0); 

      if(a.getAttackType() == IAttack.AttackType.Melee){ 
       attackType.setBackgroundResource(R.drawable.melee); 
      } 
      else if(a.getAttackType() == IAttack.AttackType.Ranged){ 
       attackType.setBackgroundResource(R.drawable.range); 
       attackType.setText(a.getMinRange() + "-" + a.getMaxRange()); 
       attackType.setTextColor(Color.WHITE); 
       attackType.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); 
       attackType.setTypeface(Typeface.DEFAULT_BOLD); 
      } 

      layout.addView(attackType); 
      attackColumn.addView(layout); 
     } 
    } 

} 

Вот мой адаптер

public class CardAdapter extends RecyclerView.Adapter<CardHolder> { 
    private ArrayList<ICard> cards; 

    public CardAdapter(ArrayList<ICard> cards){ 
     super(); 
     this.cards = cards; 
    } 
    @Override 
    public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_card_row, parent, false); 
     return new CardHolder(itemView); 
    } 

    @Override 
    public void onBindViewHolder(CardHolder holder, int position) { 
     ICard card = cards.get(position); 
     holder.setCard((Card)card); 
    } 

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

В методе setCard я запросное объект карты и добавляя различные элементы пользовательского интерфейса, соответственно. Кажется, что он работает нормально в течение короткого периода времени, но быстро становится очевидным, что элементы пользовательского интерфейса, которые динамически добавляются, дублируют себя. Когда вы прокручиваете вверх и вниз, их будет больше и больше.

Я делаю что-то неправильно, динамически добавляя код интерфейса в onBindViewHolder адаптера? Если да, то каков был бы правильный способ сделать то, что я пытаюсь сделать?

+0

Даже у меня такая же проблема. У вас есть решение для этого? –

ответ

0

Просто удалите все виды из вашего родителя на onBindViewHolder().