ArrayList限制为可容纳10个值 [英] ArrayList Limit to hold 10 Values
本文介绍了ArrayList限制为可容纳10个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的代码中使用了 ArrayList
,该字段由 EditText
字段填充,但是我想限制 ArrayList
以便仅保留10个值.添加10个值后,如果另一个尝试添加,我只需要它不添加到 Array
中即可.任何人都知道如何做到这一点吗?
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 hold 10 values. After 10 values have been added if another tries to get added I just need it to not add into the Array
. Anyone got any ideas how to do that?
private static ArrayList<String> playerList = new ArrayList<String>();
推荐答案
在您的处理程序方法中:
In your handler method:
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
内的大小,而不是外部:
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
}
}
});
这篇关于ArrayList限制为可容纳10个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文