如何将 List<String> 用于 ArrayAdapter 值(Java、Android)
How do I use List<String> for ArrayAdapter values (Java, Android)
我正在尝试在应用程序 运行 时更新 listView 项目。我可以通过使用 String[] 而不是 List 来让它工作,但我的目标是让它与 List 一起工作,这样我就可以在应用程序为 运行.
时向 listView 添加更多项目
private List<String> items;
我已经为 MainActivity 创建了一个列表 class。
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, items);
listView.setAdapter(adapter);
这行不通。我试图用 items.ToArray() 来解决问题,但没有找到解决方案。尝试使用谷歌搜索,但 Google 的所有结果仅重定向到显示如何制作 listView 的教程,并且每个教程都基于 String[] 数组。
如果我使用以下应用程序工作正常:
private String[] items = {"Banana", "Lime"};
我希望在用户使用以下方式将项目添加到列表时实时管理项目:"adapter.notifyDataSetChanged();"
我是 Java 的新手,尤其是 Android 开发方面的初学者,因此非常感谢您的帮助。
您有两种方法可以做到这一点:
- 将您的列表转换为数组(您可以找到一个很好的示例 here)。
- 创建自己的 Adapter 并使用 List(另一个很好的例子 here)。
第一种方法:
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
第二种方法:
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
我正在尝试在应用程序 运行 时更新 listView 项目。我可以通过使用 String[] 而不是 List 来让它工作,但我的目标是让它与 List 一起工作,这样我就可以在应用程序为 运行.
时向 listView 添加更多项目private List<String> items;
我已经为 MainActivity 创建了一个列表 class。
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, items);
listView.setAdapter(adapter);
这行不通。我试图用 items.ToArray() 来解决问题,但没有找到解决方案。尝试使用谷歌搜索,但 Google 的所有结果仅重定向到显示如何制作 listView 的教程,并且每个教程都基于 String[] 数组。
如果我使用以下应用程序工作正常:
private String[] items = {"Banana", "Lime"};
我希望在用户使用以下方式将项目添加到列表时实时管理项目:"adapter.notifyDataSetChanged();"
我是 Java 的新手,尤其是 Android 开发方面的初学者,因此非常感谢您的帮助。
您有两种方法可以做到这一点:
- 将您的列表转换为数组(您可以找到一个很好的示例 here)。
- 创建自己的 Adapter 并使用 List(另一个很好的例子 here)。
第一种方法:
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
第二种方法:
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}