我应该如何为大型ListView列表定义图标(+100项)

时间:2015-02-08 13:29:52

标签: android arrays listview

我一直在尝试创建一个ListView,并且我已经成功创建了一个。但是我的ListView现在对列表中的每个项目使用相同的图标。当我一直在寻找答案时,人们刚刚展示了少于10个项目的列表示例。但是我的清单包含了超过100个项目。

对于文本,我刚在string.xml中创建了一个字符串数组,并使用

检索它们
Resources res = getResources();
String[] list_of_names = res.getStringArray(R.array.names);

但我如何用图标做同样的事情呢?可以/我应该在一个单独的文件中定义它们,就像我对我的字符串数组一样吗?我的图标在我的drawables文件夹中。

另外,我是否应该为列表图标使用一组图像?还有另一种方式吗?

感谢您的帮助!

编辑:

CustomAdapter.java

class CustomAdapter extends ArrayAdapter<String> {

CustomAdapter(Context context, String[] listNames) {
    super(context, R.layout.list_item_copy, listNames);
}

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.list_item_copy, parent, false);

        String item = getItem(position);
        TextView textView = (TextView) customView.findViewById(R.id.name);
        ImageView imageView = (ImageView) customView.findViewById(R.id.icon);

        textView.setText(item);
        imageView.setImageResource(R.drawable.icon_red);
        return customView;
    }
}

MainActivity.java

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        Resources res = getResources();
        String[] listNames = res.getStringArray(R.array.names);

        ArrayAdapter<String> adapter = new CustomAdapter(getActivity(), listNames);
        ListView list = (ListView) rootView.findViewById(R.id.nameList);
        list.setAdapter(adapter);

        return rootView;
    }

这会为所有项目创建一个包含相同图标的列表,但图标应该不同。

如果它有任何区别,我已经按照新波士顿的这个教程:http://youtu.be/nOdSARCVYic?list=PL6gx4Cwl9DGBsvRxJJOzG4r4k_zLKrnxl

1 个答案:

答案 0 :(得分:0)

您可以在strings.xml中定义:

<array name="drawerIcons">
    <item>@drawable/ic_action_design</item>
    <item>@drawable/ic_action_develop</item>
</array>

您可以将它添加到ArrayList中:

ArrayList<DrawerItem> drawerItems = new ArrayList<>();
    final String[] drawerTitles = getResources().getStringArray(R.array.drawer);
    final TypedArray drawerIcons = getResources().obtainTypedArray(R.array.drawerIcons);
    for (int i = 0; i < drawerTitles.length; i++) {
        drawerItems.add(new DrawerItem(drawerTitles[i], drawerIcons.getDrawable(i)));
    }

这是我在导航抽屉列表视图中使用的DrawerItem类:

    public class DrawerItem {
    String title;
    Drawable icon;

    public DrawerItem(String title, Drawable icon) {
        this.title = title;
        this.icon = icon;
    }

    public String getTitle() {
        return title;
    }

    public Drawable getIcon() {
        return icon;
    }
}

你应该更改你的arralist(字符串)。使用DrawerItems代码创建ArrayList(如果你想要多个textview和imageview,你可以向该类添加更多元素。