0

我有一个自定义适配器和一个 ListView 并且我正在尝试将项目动态添加到其中,而不是动态地将每个项目硬编码,我需要使用 for 循环或排序添加项目。

这是主要功能:

        Arrivals arrivals_data[] = new Arrivals[] {
                new Arrivals(getResources().getIdentifier(
                        flightInfoArray[1][2].toLowerCase(), "drawable",
                        getPackageName()), "Time:" + flightInfoArray[1][1]
                        + " | Flight:  " + ""
                        + flightInfoArray[1][2].toUpperCase() + ""
                        + flightInfoArray[1][3] + " | From:"
                        + flightInfoArray[1][5] + " | Via:"
                        + flightInfoArray[1][6] + " | Remarks:"
                        + flightInfoArray[1][7] + " | ETA:"
                        + flightInfoArray[1][8]),

    };

    ArrivalsAdapter adapter = new ArrivalsAdapter(this,
            R.layout.listview_arrivals_item_row, arrivals_data);

    listView1 = (ListView) findViewById(R.id.listView1);

    listView1.setAdapter(adapter);

    listView1.setLongClickable(true);

    registerForContextMenu(listView1);

例如:

   Arrivals arrivals_data[] = new Arrivals[] {
         for (int i = 0; i < flightInforArray.length; i++) {
                new Arrivals(getResources().getIdentifier(
                        flightInfoArray[i][2].toLowerCase(), "drawable",
                        getPackageName()), "Time:" + flightInfoArray[i][1]
                        + " | Flight:  " + ""
                        + flightInfoArray[i][2].toUpperCase() + ""
                        + flightInfoArray[i][3] + " | From:"
                        + flightInfoArray[i][5] + " | Via:"
                        + flightInfoArray[i][6] + " | Remarks:"
                        + flightInfoArray[i][7] + " | ETA:"
                        + flightInfoArray[i][8]),

        }        
   };

那当然不能这样做,有什么想法吗?

先感谢您!

4

1 回答 1

0

您本质上想要Arrivals动态创建一个数组。你可以这样做:

ArrayList<Arrivals> arrivals = new ArrayList<Arrivals>();
for (int i = 0; i < flightInfoArray.length; i++) {
     Arrivals new_arrival = new Arrivals(getResources().getIdentifier(
       flightInfoArray[i][2].toLowerCase(), "drawable",
       getPackageName()), "Time:" + flightInfoArray[i][1]
       + " | Flight:  " + ""
       + flightInfoArray[i][2].toUpperCase() + ""
       ....);

     arrivals.add(new_arrival);
}
//now convert the arraylist to array
Arrivals[] arrivals_data = new Arrivals[arrivals.size()];
arrivals_data = arrivals.toArray(arrivals_data);

现在您可以arrivals_data像往常一样将阵列提供给阵列适配器。

ArrivalsAdapter adapter = new ArrivalsAdapter(this,
        R.layout.listview_arrivals_item_row, arrivals_data);
于 2013-05-02T22:51:20.990 回答