1

Following is the code from RecyclerView onBindViewHolder method.

Inside the recycler view I am creating a button Dynamically as shown below.

@Override
  public void onBindViewHolder(final ViewHolder holder, final int position) {
          .
          .
          .
        Button button1 = new Button(context);
        holder.phoneContainer.addView(button1);
}

When I Scroll the App in Device (when Running in real Device), The Button is created again.

It is supposed to attach 1 button in every cardview but when ever I scroll the button is created.

Any way to remove the existing views inside holder.phoneContainer or

creating only once?

abdul rashid
  • 730
  • 9
  • 21

2 Answers2

2

You should remove the views inside your container and the add your button.

        holder.phoneContainer.removeAllViews();
        Button button1 = new Button(context);
        LinearLayout.LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        holder.phoneContainer..addView(button1, params);
Johanna A.
  • 63
  • 7
1

If there's only a single View inside the phoneContainer you can do:

holder.phoneContainer.removeAllViews();
holder.phoneContainer.addView(button1);
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
  • What if there is More than one button ? – abdul rashid May 09 '16 at 17:24
  • 1
    You will have to keep a reference to the added `button1` inside your `ViewHolder` and use `holder.phoneContainer.removeView(button1)`. Although I must say, using an `Adapter` THIS WAY is pretty terrible. – Bartek Lipinski May 09 '16 at 17:25
  • I have 3 Buttons created Dynamically. Using `removeAllViews()` solved the problem. Will it consume more memory removing all views everytime during scroll? [RecyclerView.Adapter Documentation](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html) – abdul rashid May 09 '16 at 17:27
  • Manipulating your `Views` (which includes both `adding` and `removing` `Views` to and from hierarchy) will use quite a lot of resources if you do it in `onBindViewHolder `. You should try to omit dynamic addition of `Views` inside `onBindViewHolder` in general. – Bartek Lipinski May 09 '16 at 17:31
  • Then how to create and attach views based on custom API response? Other suggestions? – abdul rashid May 09 '16 at 17:32
  • You can do that in a million different ways. Everything depends on your particular case. My best guess is, in your case you could do it elegantly with a proper `Adapter` that can inflate multiple types of `Views`. There are tons of topics here on SO about that. For example [this one](http://stackoverflow.com/questions/25914003/recyclerview-and-handling-different-type-of-row-inflation) – Bartek Lipinski May 09 '16 at 17:36