在Android Studio中填充ArrayList,最好的方法(初级)?

时间:2016-03-11 07:06:58

标签: java android listview arraylist

我是Android Studio甚至java的新手,所以我有一些基本的问题。 我想用有关动物的数据填充ListView。

最好的方法是什么? 例如,我有一个猫和狗类包含价格标签(两个不同的奖品)。现在我想在我的ListView中显示猫和狗以及各自的奖品。

如何正确设置?我不确定如何在ArrayList中获取该信息,因此可以将其传输到ListView。

希望你们能在那里支持我一点。谢谢:))

1 个答案:

答案 0 :(得分:0)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initial the arraylist
        List<Animal> animals = new ArrayList<Animal>() {{
            add(new Dog());
            add(new Cat());
        }};
        // get a list view
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(new MyAdapter(animals));
    }

    // this is your custom adapter
    static class MyAdapter<Animal> extends BaseAdapter {

        private List<Animal> animalList;

        public MyAdapter(List<Animal> animalList) {
            this.animalList = animalList;
        }

        @Override
        public int getCount() {
            return animalList.size();
        }

        @Override
        public Animal getItem(int position) {
            return animalList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Animal animal = getItem(position);
            if(animal instanceof Dog){
                // do dog things
            }else if(animal instanceof Cat){
                // do cat things
            }
            // you might want inflate your custom item view at here
            return null;
        }
    }

    static interface Animal {
        // customize your interface as you wish
    }

    static class Cat implements Animal {

    }

    static class Dog implements Animal {

    }
}