Android ArrayList.size返回notfound

0 size android vector

我的应用程序向向量添加一个整数值,然后想知道该向量的大小.

if(nearSelected||middleSelected||farSelected){
    ArrayList<Integer> distance = new ArrayList<Integer>();

    //Which distance(s) has the user selected?
    if(nearSelected){distance.add(1);}
    if(middleSelected){distance.add(2);}
    if(farSelected){distance.add(3);}       

    //Attempt to display the number of choices picked to the user
    try {
        Toast.makeText(getBaseContext(), distance.size(), Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
       Log.i(LOG_TAG, e.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,试图获得distance.size()原因NotFoundException.代码的所有其他部分运行正常,只是这部分崩溃.搞砸了哪里?

K-b*_*llo 6

Distance.size()它不是导致Resources.NotFoundException它的原因Toast.makeText.当使用整数作为参数调用时,它会查找具有该整数作为id 的字符串资源.如果你想将数字显示为一个字符串,那么你必须这样说:

Toast.makeText(getBaseContext(), Integer.toString(distance.size()), Toast.LENGTH_SHORT).show();
Run Code Online (Sandbox Code Playgroud)