ArrayList Limit to hold 10 Values

前端 未结 4 580
忘掉有多难
忘掉有多难 2021-01-04 17:51

I am using an ArrayList within my code which gets populated by a EditText field but I am wanting to limit the ArrayList so it can only

4条回答
  •  失恋的感觉
    2021-01-04 18:43

    In your handler method:

    if(playerList.size() < 10) {
       // playerList.add
    } else {
       // do nothing
    }
    

    Edit: Your mistake is here:

    if(playerList.size() < 10) {
    
        Button confirm = (Button) findViewById(R.id.add);
        confirm.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        EditText playername = (EditText) findViewById(R.id.userinput);
        playerList.add(playername.getText().toString());
        adapter.notifyDataSetChanged();
        playername.setText("");
    
        }});
    } else {
           // do nothing
    }
    

    You should check the size inside the onClickListener, not outside:

        Button confirm = (Button) findViewById(R.id.add);
        confirm.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                EditText playername = (EditText) findViewById(R.id.userinput);
                if(playerList.size() < 10) {
                   playerList.add(playername.getText().toString());
                   adapter.notifyDataSetChanged();
                   playername.setText("");
                } else {
                    // do nothing
                }
            }
         });
    

提交回复
热议问题