3min初识ListView(1)-BaseAdapter方法实现

ListViewAndroid件开发中非常重要组件之一,基本上是个软件基本都会使用ListView 

今天我们初始ListView并实现其适配器BaseAdapter的相关方法。

先看ListView官方API:

A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.

我们在布局文件中添加ListView控件:

    <ListView
        android:id="@+id/test_lv_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

ps:Android中所有控件都可以在xml中显示出来,所有控件首字母都必须大写,初始化findViewById。

在代码中初始化控件:

    private ListView test_lv_main;
···
    test_lv_main = (ListView) findViewById(R.id.test_lv_main);

ListView控件比较特殊,显示数据需要适配器,我们跟随刚才的API进入ListAdapter接口,

Extended Adapter that is the bridge between a ListView and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.

然而实现该接口后发现要实现的方法太多,所以,转而寻找他的实现类。

我们看一下他的子类:

Known Indirect Subclasses

这里我们选择BaseAdapter并实现他的4个方法。

Common base class of common implementation for an Adapter that can be used in both ListView (by implementing the specializedListAdapter interface} and Spinner (by implementing the specialized SpinnerAdapter interface.

这里重点说一下getCount方法,它决定我们在ListView中展示几条数据,这里我们直接返回10,即展示10条。

还有getView方法,它获取一个View并将其作为ListView的一个条目展示出来,这里我们自定义一个TextView。

    private class testAdapter extends BaseAdapter{

        //一共展示多少条数据
        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

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

        //获取View,作为ListView的一个条目显示
        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            TextView tv = new TextView(MainActivity.this);
            tv.setText("权兴权意-" + position);
            return tv;
        }
    }


最后我们在代码中为ListView绑定适配器,

        test_lv_main.setAdapter(new testAdapter());

运行程序,效果就出来了:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值