java – ArrayList限制为保存10个值

栏目: Java · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/8969805/arraylist-limit-to-hold-10-values
我在我的代码中使用了一个ArrayList,它由EditText字段填充,但我想限制ArrayList,因此它只能容纳10个值.添加10个值后,如果另一个尝试添加,我只需要它不添加到数组中.任何人有任何想法如何做到这一点?
private static ArrayList<String> playerList = new ArrayList<String>();

在你的处理程序方法:

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

编辑:你的错误在这里:

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
}

您应该检查onClickListener内部的大小,而不是外部:

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
            }
        }
     });

翻译自:https://stackoverflow.com/questions/8969805/arraylist-limit-to-hold-10-values


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Computer Vision with Python

Programming Computer Vision with Python

Jan Erik Solem / O'Reilly Media / 2012-6-22 / USD 39.99

If you want a basic understanding of computer vision's underlying theory and algorithms, this hands-on introduction is the ideal place to start. As a student, researcher, hacker, or enthusiast, you'll......一起来看看 《Programming Computer Vision with Python》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具