ListView

发布于:2024-07-11 ⋅ 阅读:(23) ⋅ 点赞:(0)

样式

适配器Adapter

1、简单列表实现

要有页面+数据+适配器

实现以ListView展示数据,并能够跳转到其他Activity,给了展示数据的点击和长按事件。

1、MainActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void toArrayTest(View view) {
        Intent intent = new Intent(this, ArrayListActivity.class);
        startActivity(intent);
    }
}

2、ArrayListActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ArrayListActivity extends AppCompatActivity {

    private ListView mListView;
    private List<String> mStringList;
    private ArrayAdapter<String> mArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_array_list);

        mListView = findViewById(R.id.listview);
        mStringList = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            mStringList.add("这是条目"+i);
        }

        mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStringList);
        mListView.setAdapter(mArrayAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(ArrayListActivity.this, "点击了条目" + i, Toast.LENGTH_SHORT).show();
                }
            });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(ArrayListActivity.this, "长按了条目" + i, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        
    }
}

3、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="10dp">
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Array列表"
            android:onClick="toArrayTest"
            android:textAllCaps="false"/>

    </LinearLayout>

</ScrollView>

4、activity_array_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ArrayListActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:divider="@android:color/black"
        android:dividerHeight="1dp"
        android:scrollbars="none" />

</LinearLayout>

2、图文列表实现

注:实现其需要两个布局文件,一个整体布局,一个局部布局(把局部布局导入适配器即可)

1、在MainActivity添加如下代码

public void toSimpleListTest(View view) {
        Intent intent = new Intent(this, SimpleListActivity.class);
        startActivity(intent);
    }

2、SimpleListActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleListActivity extends AppCompatActivity {
    private ListView listView;
    private SimpleAdapter simpleAdapter;
    private List<Map<String, Object>> mList;

    private int[] images = {
            R.drawable.test1,
            R.drawable.test2,
            R.drawable.test3,
            R.drawable.test4,
            R.drawable.test5,
            R.drawable.test6,
            R.drawable.test7,
            R.drawable.test8,
            R.drawable.test9,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_list);
        listView = findViewById(R.id.lv);
        mList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            Map<String, Object> m = new HashMap<>();
            m.put("image", images[i % images.length]);
            m.put("title", "标题" + i);
            m.put("content", "内容" + i);

            mList.add(m);
        }
        simpleAdapter = new SimpleAdapter(
                this,
                mList,
                R.layout.list_item_layout,
                new String[]{"image", "title", "content"},
                new int[]{R.id.iv_img, R.id.tv_title, R.id.tv_content}
        );
        listView.setAdapter(simpleAdapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Map<String, Object> map = mList.get(position);
            String title = (String) map.get("title");
            String content = (String) map.get("content");
            int image = (int) map.get("image");
            String msg = "title: " + title + "\ncontent: " + content + "\nimage: " + image;
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        });

    }
}

3、activity_simple_list.xml(整体布局样式)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SimpleListActivity">

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

</LinearLayout>

4、list_item_layout.xml(每个小item的样式)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingTop="5dp"
    android:paddingRight="10dp"
    android:paddingBottom="5dp">

    <ImageView
        android:id="@+id/iv_img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher_background" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/iv_img"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="雨中漫步"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/iv_img"
        android:ellipsize="end"
        android:maxLines="3"
        android:text="人生就像一场旅行,不必在乎目的地,在乎的是沿途的风景以及看风景的心情,让心灵去旅行"
        android:textSize="16sp" />
</RelativeLayout>

样式效果如图:图文并茂

5、在activity_main.xml中添加如下代码

 <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Simple列表"
            android:onClick="toSimpleListTest"
            android:textAllCaps="false"/>

3、图文复杂列表实现

1、在MainActivity.java中添加如下代码

 public void toBaseListTest(View view) {
        Intent intent = new Intent(this, BaseAdapterActivity.class);
        startActivity(intent);
    }

2、创建ItemBean类

package com.example.myapplication.bean;

public class ItemBean {
    private String title;
    private String content;
    private int imageId;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    @Override
    public String toString() {
        return "ItemBean{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", imageId=" + imageId +
                '}';
    }
}

3、创建自定义适配器MyAdapter

package com.example.myapplication.adapter;

import android.content.Context;
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 com.example.myapplication.R;
import com.example.myapplication.bean.ItemBean;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    private List<ItemBean> mBeanList;
    private LayoutInflater mLayoutInflater;
    private Context mContext;

    public MyAdapter(List<ItemBean> beanList, Context context) {
        this.mBeanList = beanList;
        this.mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    //返回列表项的数量
    public int getCount() {
        return mBeanList.size();
    }

    @Override
    //返回指定位置的列表项数据
    public Object getItem(int i) {
        return mBeanList.get(i);
    }

    @Override
    //返回指定位置的列表项的ID
    public long getItemId(int i) {
        return i;
    }

    @Override
    //返回列表项的视图
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = mLayoutInflater.inflate(R.layout.list_item_layout, viewGroup, false);
        ImageView imageView = view.findViewById(R.id.iv_img);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        TextView tvContent = view.findViewById(R.id.tv_content);

        //为控件填充数据
        ItemBean itemBean = mBeanList.get(i);
        imageView.setImageResource(itemBean.getImageId());
        tvTitle.setText(itemBean.getTitle());
        tvContent.setText(itemBean.getContent());

        return view;
    }
}

优化适配器MyAdapter2

主要判断view是否为空,如果为空,则获取image、title、content,然后把它们放到viewHolder里,相当于一个缓存,若不为空,则复用缓存的数据,提高运行速度。

package com.example.myapplication.adapter;

import android.content.Context;
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 com.example.myapplication.R;
import com.example.myapplication.bean.ItemBean;

import java.util.List;

public class MyAdapter2 extends BaseAdapter {
    private List<ItemBean> mBeanList;
    private LayoutInflater mLayoutInflater;
    private Context mContext;

    public MyAdapter2(List<ItemBean> beanList, Context context) {
        this.mBeanList = beanList;
        this.mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    //返回列表项的数量
    public int getCount() {
        return mBeanList.size();
    }

    @Override
    //返回指定位置的列表项数据
    public Object getItem(int i) {
        return mBeanList.get(i);
    }

    @Override
    //返回指定位置的列表项的ID
    public long getItemId(int i) {
        return i;
    }

    @Override
    //返回列表项的视图
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = new ViewHolder();
        if (view == null) {
            view = mLayoutInflater.inflate(R.layout.list_item_layout, viewGroup, false);

            ImageView imageView = view.findViewById(R.id.iv_img);
            TextView tvTitle = view.findViewById(R.id.tv_title);
            TextView tvContent = view.findViewById(R.id.tv_content);

            viewHolder.imageView = imageView;
            viewHolder.tvTitle = tvTitle;
            viewHolder.tvContent = tvContent;
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();
        }


        //为控件填充数据
        ItemBean itemBean = mBeanList.get(i);
        viewHolder.imageView.setImageResource(itemBean.getImageId());
        viewHolder.tvTitle.setText(itemBean.getTitle());
        viewHolder.tvContent.setText(itemBean.getContent());

        return view;
    }

    class ViewHolder {
        ImageView imageView;
        TextView tvTitle;
        TextView tvContent;
    }
}

4、创建BaseAdapterActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.myapplication.adapter.MyAdapter;
import com.example.myapplication.adapter.MyAdapter2;
import com.example.myapplication.bean.ItemBean;

import java.util.ArrayList;
import java.util.List;

public class BaseAdapterActivity extends AppCompatActivity {

    private ListView mListView;
    private List<ItemBean> mBeanList;
    private MyAdapter2 mMyAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_adapter);
        mListView = findViewById(R.id.lv);
        initView();
        initData();
        initEvent();
    }

    private void initEvent() {
        mMyAdapter = new MyAdapter2(mBeanList,this);
        mListView.setAdapter(mMyAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemBean bean = mBeanList.get(i);
                String title = bean.getTitle();
                Toast.makeText(BaseAdapterActivity.this,"你点击了" + i + title,Toast.LENGTH_SHORT).show();
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                return false;
            }
        });
    }

    private void initData() {
        mBeanList = new ArrayList<>();

        ItemBean newsBean1 = new ItemBean();
        newsBean1.setTitle("雨中漫步");
        newsBean1.setContent("人生就像一场旅行,不必在乎目的地,在乎的是沿途的风景以及看风景的心情,让心灵去旅行。\n只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n背着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。");
        newsBean1.setImageId(R.drawable.test1);

        ItemBean newsBean2 = new ItemBean();
        newsBean2.setTitle("林间穿梭");
        newsBean2.setContent("只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n路旁边浪似地滚着高高低低的黄土。太阳给埋在黄土里,发着肉红色。可是太阳还烧得怪起劲的,把他们的皮肉烧得变成紫黑色,似乎还闻得到一股焦味儿。");
        newsBean2.setImageId(R.drawable.test2);

        ItemBean newsBean3 = new ItemBean();
        newsBean3.setTitle("旅行花海");
        newsBean3.setContent("只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n背着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。\n" +
                "\n" +
                "想呼吸着每座城市的空气,想感受着每座城市的人儿,想看着每座城市的风景。");
        newsBean3.setImageId(R.drawable.test3);


        ItemBean newsBean4 = new ItemBean();
        newsBean4.setTitle("非平衡的线");
        newsBean4.setContent("一根线如果绷得太紧,总有一天会断裂,一颗心若是禁锢得太久,总有一天会失去平衡,我们需要放飞心灵,让心翱翔在自由的太空。每个人在他的人生发轫之初,总有一段时光,没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。");
        newsBean4.setImageId(R.drawable.test4);

        ItemBean newsBean5 = new ItemBean();
        newsBean5.setTitle("说走就走");
        newsBean5.setContent("说走就走的旅行,要么缘由幸福稳定和宽裕,要么祸起无力无奈和逃避。\n在旅途中,我遇见了你,你我相识是缘分!看着你手中的戒指,你说,你可以把它取下来吗?当我要取的时候,你淘气的躲开了,你说只有有缘人才可以取下,我看着你手中的戒指,想做你的有缘人,可是我知道结果是惨淡的,但还是心存希望!");
        newsBean5.setImageId(R.drawable.test5);

        ItemBean newsBean6 = new ItemBean();
        newsBean6.setTitle("美好的记忆");
        newsBean6.setContent("旅行不在乎终点,而是在意途中的人和事还有那些美好的记忆和景色。人生就是一次充满未知的旅行,在乎的是沿途的风景,在乎的是看风景的心情,旅行不会因为美丽的风景终止。走过的路成为背后的风景,不能回头不能停留,若此刻停留,将会错过更好的风景,保持一份平和,保持一份清醒。享受每一刻的感觉,欣赏每一处的风景,这就是人生。(作者:《遇到另一种生活》");
        newsBean6.setImageId(R.drawable.test6);

        ItemBean newsBean7 = new ItemBean();
        newsBean7.setTitle("久违的感动");
        newsBean7.setContent("人生最好的旅行,就是你在一个陌生的地方,发现一种久违的感动。人生最好的旅行,就是你在一个陌生的地方,发现一种久违的感动");
        newsBean7.setImageId(R.drawable.test7);

        ItemBean newsBean8 = new ItemBean();
        newsBean8.setTitle("流浪日记");
        newsBean8.setContent("着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。\n每个人在他的人生发轫之初,总有一段时光,没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。");
        newsBean8.setImageId(R.drawable.test8);

        ItemBean newsBean9 = new ItemBean();
        newsBean9.setTitle("山的尽头");
        newsBean9.setContent("在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。\n在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。\n在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。");
        newsBean9.setImageId(R.drawable.test9);

        ItemBean newsBean10 = new ItemBean();
        newsBean10.setTitle("秦河魅影");
        newsBean10.setContent("秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。\n秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。\n秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。");
        newsBean10.setImageId(R.drawable.test10);

        mBeanList.add(newsBean1);
        mBeanList.add(newsBean2);
        mBeanList.add(newsBean3);
        mBeanList.add(newsBean4);
        mBeanList.add(newsBean5);
        mBeanList.add(newsBean6);
        mBeanList.add(newsBean7);
        mBeanList.add(newsBean8);
        mBeanList.add(newsBean9);
        mBeanList.add(newsBean10);
        mBeanList.add(newsBean1);
        mBeanList.add(newsBean2);
        mBeanList.add(newsBean3);
        mBeanList.add(newsBean4);
        mBeanList.add(newsBean5);
        mBeanList.add(newsBean6);
        mBeanList.add(newsBean7);
        mBeanList.add(newsBean8);
        mBeanList.add(newsBean9);
        mBeanList.add(newsBean10);
    }

    private void initView() {
    }
}

5、activity_base_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SimpleListActivity">

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

</LinearLayout>