Android day_06 (ListView的入门使用 了解数据适配Adapter以及打气筒的使用)

1)getView(int  View ViewGroup )方法的写法以及三中获取打气筒服务的方式

public View getView(int i, View view, ViewGroup viewGroup) {
            //想办法吧 自己创建的布局 转化成一个View对象
            View v;
            if (view == null){
                //创建一个View对象  可以通过打气筒(inflate)把一个布局文件文件转化成View对象
                //【☆☆☆☆】第一种获取打气筒服务的方式
                //第一个参数上下文  第二个想转化的布局文件 第三个为ViewGroup一般不用写null
                //v=View.inflate(getApplicationContext(),R.layout.item,null);
                //【☆☆☆☆】第二种获取打气筒服务的方式
                //v=LayoutInflater.from(getApplicationContext()).inflate(R.layout.item,null);
                //【☆☆☆☆】第三种获取打气筒服务的方式
                LayoutInflater inflater=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                v=inflater.inflate(R.layout.item,null);
            }else{
                v=view;
            }
            return v;
        }

2)ListView 的入门及优化

      ListView在定义属性时的注意事项:宽高最好都定义成填充父窗体算是对ListView的优化,否则会有一些奇怪的现象。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView lv=findViewById(R.id.lv);
        //在ListView显示数据需要调用ListView的数据适配器Adapter
        lv.setAdapter(new MylistAdapter());
    }
    /*定义ListView的数据适配器  需要实现 ListAdapter接口但是因为该接口中未实现的方法太多
     *可以继承一个实现了该接口的类 BaseAdapter
     */
    private class MylistAdapter extends BaseAdapter{
        @Override
        //一共有多少条数据需要显示
        public int getCount() {
            return 50;
        }
        @Override
        //返回指定i位置上的对象  i是从0开始的
        public Object getItem(int i) {
            return null;
        }
        @Override
        // //返回指定i位置上对应的id  i是从0开始的
        public long getItemId(int i) {
            return 0;
        }
        //获取一个View  作为 ListView 的一个条目出现
        public View getView(int i, View view, ViewGroup viewGroup) {
            TextView tv;
             //优化后 如果有缓存的View对象 就不创建新的 TextView直接使用 不会导致溢出
            if (view == null){
                tv=new TextView(MainActivity.this);               
                System.out.println("创建新对象"+i);
            }else{
                tv=(TextView) view;           
                System.out.println("复用历史缓存对象"+i);
            }
            //未优化 当快速滑动界面是可能会出现缓存溢出 导致程序挂掉
            //System.out.println("getView"+i);
            //TextView tv=new TextView(MainActivity.this);
            tv.setText("heheheheheheheheh--------"+i);
            return tv;
        }

3)其他适配器(Adapter)的使用

SimleAdapter的使用第一个参数上下文  第二个 为一个Map 带三个布局文件

第四个显示的列名就是Map的键 第五个在哪里显示写布局的id

ArrAdapter的使用

猜你喜欢

转载自blog.csdn.net/depths_t/article/details/81183753
今日推荐