Skip to content
Advertisement

Android Studio – How do I make my RecyclerView contain more items after a button press?

I’ve created a RecyclerView with editTexts which size is defined by an integer in the adapters constructor, however now I want to implement a Button that increases that integer by one and that way adds another editText to my recyclerView. The problem is that I don’t know how to update the size of the recyclerView after it’s first created, here is the code and what I’ve tried so far.

The MainActivity:

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private int playerAmount;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    playerAmount = 6;

    recyclerView = findViewById(R.id.recyclyerViewNames);

    MyAdapter myAdapter = new MyAdapter(this, playerAmount);

    recyclerView.setAdapter(myAdapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

public void addPlayers(View view){
    playerAmount++;
    recyclerView.getAdapter().notifyDataSetChanged();
    Log.d("players",String.valueOf(playerAmount));
    Log.d("players in adapter",String.valueOf(recyclerView.getAdapter().getItemCount()));
}

}

Adapter class:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

Context context;
int playerAmount;

public MyAdapter(Context ct, int players){
    context = ct;
    playerAmount = players;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.enter_name, parent, false);

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

}

@Override
public int getItemCount() {
    return playerAmount;
}

public class ViewHolder extends RecyclerView.ViewHolder {
    EditText editText;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        editText = itemView.findViewById(R.id.editname);
    }
}

}

Advertisement

Answer

Theoretically, you just have to update the adapter’s list and then have to call notifyDataSetChanged and everything else will be taken care by Android itself.

In your case you didn’t created a list at all. You are missing few things in your adapter implementation.

I would recommend go through this documentation https://developer.android.com/guide/topics/ui/layout/recyclerview

You will find the sample code link by Google at the end of the page and also try that to have better understanding of Recylerview, that way you will be in better position to proceed further.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement