Adapter

作者: 月影追猎者 | 来源:发表于2020-12-21 10:36 被阅读0次

    ArrayAdapter
    数组适配器,仅能显示一行文本数据

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ListView
            android:id="@+id/lv_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>
    </LinearLayout>
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    public class MainActivity extends Activity {
        // 定义要显示的数据
        private String[] datas = {"张三", "李四", "王五", "麻子", "小强"};
        private ArrayAdapter<String> adapter;
        private ListView listView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            listView = (ListView) findViewById(R.id.lv_list);
            // 初始化适配器
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, datas);
            listView.setAdapter(adapter);
        }
    }
    

    可以在value创建数组资源xml文件arrays.xml,在listview中使用entries

    <resources>
        <string-array name = "list">
            <item>张三</item>
            <item>李四</item>
            <item>王五</item>
            <item>麻子</item>
            <item>小强</item>
          </string-array>
    </resources>
    
    <ListView
        android:id="@+id/lv_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/list">
    </ListView>
    
    datas = getResources().getStringArray(R.array.list);
    
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String result = parent.getItemAtPosition(position).toString();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
        }
    });
    

    ArrayAdapter参数说明

    • 第一个参数,context上下文对象
    • 第二个参数,item样式,可以使用系统提供,可以自定义TextView
    • 第三个参数,数据源

    系统提供item样式

    • simple_list_item1,单行文本框(text)
    • simple_list_item2,两行文本框(title与text)
    • simple_list_item_checked,复选框(已选中)
    • simple_list_item_multiple_choice,复选框
    • simple_list_item_single_choice,单选框

    SimpleAdapter
    简单适配器

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ListView
            android:id="@+id/lv_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>
    </LinearLayout>
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal">
        <ImageView
            android:id="@+id/iv_image"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="5dp"/>
       <LinearLayout
           android:id="@+id/ll_info"
           android:layout_width="match_parent"
           android:layout_height="100dp"
           android:orientation="vertical"
           android:layout_marginTop="5dp"
           android:layout_marginLeft="10dp">
           <TextView
               android:id="@+id/tv_theme"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="30sp"
               android:layout_marginTop="10dp"/>
           <TextView
               android:id="@+id/tv_content"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="24dp"
               android:layout_marginTop="10dp"/>
       </LinearLayout>
    </LinearLayout>
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class MainActivity extends Activity {
        private List<Map<String,Object>> lists;
        private SimpleAdapter adapter;
        private ListView listView;
        // 定义数据
        private String[] theme = {"张三", "李四", "王五"};
        private String[] content = {"我是张三,你好", "我是李四,你好", "我是王五,你好"};
        private int[] imageViews = {R.mipmap.ic_launcher, R.mipmap.ic_account, R.mipmap.ic_password};
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            listView = (ListView) findViewById(R.id.lv_list);
            // 准备数据源
            lists = new ArrayList<>();
            for(int i = 0; i < theme.length; i++) {
                Map<String,Object> map = new HashMap<>();
                map.put("image", imageViews[i]);
                map.put("theme", theme[i]);
                map.put("content", content[i]);
                lists.add(map);
            }
            adapter = new SimpleAdapter(MainActivity.this, lists, R.layout.list_item, new String[]{"image", "theme", "content"}, new int[]{R.id.iv_image, R.id.tv_theme, R.id.tv_content});
            listView.setAdapter(adapter);
        }
    }
    

    SimpleAdapter参数说明

    • 第一个参数,上下文对象
    • 第二个参数,数据源(集合,元素类型Map)
    • 第三个参数,item布局文件
    • 第四个参数,String数组,数组元素与数据源Map的key一一对应
    • 第五个参数,int数组,item布局文件的控件id

    BaseAdapter

    import android.content.Context;
    import android.text.Layout;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class InfoAdapter extends BaseAdapter {
        private List<Message> datas;
        private Context mContext;
    
        public MyAdapter(List<Message> datas, Context mContext) {
            Datas = datas;
            this.mContext = mContext;
        }
    
        /**
         * 返回item个数
         * @return
         */
        @Override
        public int getCount() {
            return datas.size();
        }
    
        /**
         * 返回单个item对象
         * @param i
         * @return
         */
        @Override
        public Object getItem(int i) {
            return datas.get(i);
        }
    
        /**
         * 返回单个item的id
         * @param i
         * @return
         */
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        /**
         * 暂不进行优化处理
         * @param i
         * @param view
         * @param viewGroup
         * @return
         */
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(mContext).inflate(R.layout.list_item, viewGroup, false);
            ImageView iv_image = (ImageView) view.findViewById(R.id.iv_image);
            TextView tv_theme = (TextView) view.findViewById(R.id.tv_theme);
            TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
            iv_image.setImageResource(Datas.get(i).getImageId());
            tv_theme.setText(Datas.get(i).getTheme());
            tv_content.setText(Datas.get(i).getContent());
            return view;
        }
    }
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends Activity {
        private List<Message> lists;
        private InfoAdapter adapter;
        private ListView listView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            listView = (ListView) findViewById(R.id.ll_list);
            lists = new ArrayList<>();
            lists.add(new Message(R.mipmap.ic_launcher, "张三", "你好,我是张三"));
            lists.add(new Message(R.mipmap.ic_account, "李四", "你好,我是李四"));
            lists.add(new Message(R.mipmap.ic_password, "王五", "你好,我是王五"));
            adapter = new InfoAdapter(lists, MainActivity.this);
            listView.setAdapter(adapter);
        }
    }
    

    利用Listview缓存机制但findviewbyid反复使用

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 若view未被实例化,缓存池无对应缓存
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item, null);
        }
        /**
         * 获取item布局文件对应控件
         */
        ImageView imageView = (ImageView) convertView.findViewById(R.id.iv_image);
        TextView titleTextView = (TextView) convertView.findViewById(R.id.tv_theme);
        TextView contentTextView = (TextView) convertView.findViewById(R.id.tv_content);
        // 获取相应索引ItemBean对象
        ItemBean bean = mList.get(position);
        /**
         * 设置控件的对应属性值
         */
        imageView.setImageResource(bean.itemImageResId);
        titleTextView.setText(bean.itemTheme);
        contentTextView.setText(bean.itemContent);
        return convertView;
    }
    
    1. 创建bean对象,用于封装数据
    2. 在构造方法中初始化数据List
    3. 创建ViewHolder类,创建布局映射关系
    4. 判断convertView,为空则创建并设置tag,不为空则通过tag取出ViewHolder
    5. 给ViewHolder控件设置数据
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        // 若view未被实例化过,缓存池无对应缓存
        if (convertView == null) {
            viewHolder = new ViewHolder();
            // 仅需将XML转化为View,不涉及布局,第二个参数设置为null
            convertView = mInflater.inflate(R.layout.item, null);
            // 对viewHolder属性进行赋值
            viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_image);
            viewHolder.theme = (TextView) convertView.findViewById(R.id.tv_theme);
            viewHolder.content = (TextView) convertView.findViewById(R.id.tv_content);
            // 通过setTag将convertView与viewHolder关联
            convertView.setTag(viewHolder);
        } else {
            // 若缓存池有对应view缓存,则通过getTag取出viewHolder
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // 取出bean对象
        ItemBean bean = mList.get(position);
        // 设置控件的数据
        viewHolder.imageView.setImageResource(bean.itemImageResId);
        viewHolder.title.setText(bean.itemTheme);
        viewHolder.content.setText(bean.itemContent);
    
        return convertView;
    }
    // ViewHolder用于缓存控件,属性对应item布局文件控件
    class ViewHolder{
        public ImageView imageView;
        public TextView theme;
        public TextView content;
    }
    

    相关文章

      网友评论

          本文标题:Adapter

          本文链接:https://www.haomeiwen.com/subject/bmalnktx.html