-1

我正在尝试使用 Vector 从文本文件中添加文本视图,但我遇到了问题。在设置使用 Tokenizer 获取信息的数组时,我打印“mName”的值,它会从文本文件中获取所有值。但是当我将“mName”分配给 TextView 时,我只能从列表中获取最后一个名称..

这是代码:

数组和 TextFile 初始化 - :

AssetManager assets = mContext.getAssets();

    try {
        br = new BufferedReader(new InputStreamReader(
                assets.open("country_list")));
        while ((sCurrentLine = br.readLine()) != null) {
            StringTokenizer tokenizer = new StringTokenizer(sCurrentLine,
                    ",");
            int count = 0;

            String[] stringArr = new String[3];

            while (tokenizer.hasMoreTokens()) {
                String tokenOrginizer = tokenizer.nextToken();
                stringArr[count] = tokenOrginizer;
                count++;
                mVector = new Vector<Country>();

            }

            Country country = new Country(stringArr[0],
                    Integer.parseInt(stringArr[1]),
                    Integer.parseInt(stringArr[2]));
            mVector.add(country);
            System.out.println(stringArr[0]);
            for (int i = 0; i < mVector.size(); i++) {
                System.out.println("Vector : " + mVector.get(i).getmName());  
                //here i see all the values when printing
            }

GetView 方法 - :

public int getCount() {
    // TODO Auto-generated method stub
    return mVector.size();
}

@Override
public Object getItem(int item) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int itemId) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView tv;
    if (convertView == null) {
        tv = new TextView(mContext);
    } else {
        tv = (TextView) convertView;
    }

    for (int i = 0; i < mVector.size(); i++) {
        tv.setText(mVector.get(i).getmName());
        // i have a feeling that this is where i do something wrong

    }

    return tv;
}

}

4

1 回答 1

1

Vector每次getView调用该方法时,您只看到 中的最后一项是正常的,您将文本设置在for循环中,迭代所有mVector(并且您为 设置的最后一个文本TextView是 中的最后一个值Vector)。所以,而不是:

for (int i = 0; i < mVector.size(); i++) {
        tv.setText(mVector.get(i).getmName());
        // i have a feeling that this is where i do something wrong
        // your feeling is right, why the loop?!?  
}

你会想要:

//...
if (convertView == null) {
    tv = new TextView(mContext);
} else {
    tv = (TextView) convertView;
} 
tv.setText(mVector.get(position).getmName());
return tv;

另外,使用 anArrayList而不是Vector.

于 2013-01-20T08:05:04.220 回答