首页 > 其他分享 >Androidstudio开发,ListView实现通讯录联系人列表( 四)

Androidstudio开发,ListView实现通讯录联系人列表( 四)

时间:2024-08-06 09:55:12浏览次数:10  
标签:int rootView Androidstudio 通讯录 letter Override new ListView public

文章目录

1. 涉及到的技术点

  1. 数据库SQLite的使用
  2. 列表控件ListView的使用
  3. ListView事件监听
  4. 适配器BaseAdapter的使用
  5. 线性布局LinearLayoutCompat的使用

2. 发环境

  1. 开发工具:AndroidStudio
  2. 开发语言:java
  3. jdk版本:8.0+以上

3.需求分析

在上集中,实现了将通讯录联系人插入到数据库中,这集将数据库中的数据通过ListView控件,将通讯录联系人展示出来

温馨提示: 通讯录的主页是BottomNavigationView底部导航栏的形式,底部导航栏的案例,本人出了教程视频,这里就忽略掉这步的实现过程,文章最后会给到底部导航栏教程视频

4. 实现步骤

  1. 编写fragment_home.xml布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/teal_200"
        app:title="班级通讯录"
        app:titleTextColor="@color/white">


        <TextView
            android:id="@+id/create"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:padding="12sp"
            android:text="新建"
            android:textColor="@color/white" />

    </androidx.appcompat.widget.Toolbar>


    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar"
        tools:listitem="@layout/list_item" />


    <androidx.cardview.widget.CardView
        android:id="@+id/music"
        android:layout_width="58dp"
        android:layout_height="58dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="80dp"
        android:backgroundTint="@color/teal_200"
        app:cardCornerRadius="34dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:src="@drawable/baseline_library_music_24"
            android:text="音乐" />

    </androidx.cardview.widget.CardView>

</RelativeLayout>


效果图如下
在这里插入图片描述

ListView 需要一个布局文件 list_item.xml 在适配器中需要用到

  1. 编写Adapter适配器
public class MyListAdapter extends BaseAdapter {
        private List<StudentInfo> mStudentInfoList = new ArrayList<>();

        public void setStudentList(List<StudentInfo> studentInfoList) {
            mStudentInfoList = studentInfoList;
            notifyDataSetChanged();
        }

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

        @Override
        public StudentInfo getItem(int i) {
            return mStudentInfoList.get(i);
        }

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            //加载布局文件
            View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item, null);
            //初始化控件
            TextView username = rootView.findViewById(R.id.username);
            TextView mobile = rootView.findViewById(R.id.mobile);
            TextView class_name = rootView.findViewById(R.id.class_name);
            TextView first_letter = rootView.findViewById(R.id.first_letter);
            //绑定数据
            StudentInfo studentInfo = getItem(i);
            username.setText(studentInfo.getUsername());
            mobile.setText(studentInfo.getMobile());
            class_name.setText(studentInfo.getClass_name());
            //取名字的第一个字显示
            String letter = studentInfo.getUsername().substring(0, 1);
            first_letter.setText(letter);

            // 创建Random类的实例
            Random random = new Random();
            // 生成1-4之间的随机数
            int randomNumber = random.nextInt(4) + 1;
            if (randomNumber == 1) {
                first_letter.setBackgroundColor(Color.parseColor("#ff6161"));
            } else if (randomNumber == 2) {
                first_letter.setBackgroundColor(Color.parseColor("#00cee5"));
            } else if (randomNumber == 3) {
                first_letter.setBackgroundColor(Color.parseColor("#ffb120"));
            } else {
                first_letter.setBackgroundColor(Color.parseColor("#7484fc"));
            }

            return rootView;
        }
    }

温馨提示:StudentInfo实体,在第三集中有讲

5. 代码实现全部过程

public class HomeFragment extends Fragment {
    private View rootView;

    private ListView listview;
    private MyListAdapter mListAdapter;
    private StudentDb mStudentDb;

    private int currentIndex = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        //初始化控件
        listview = rootView.findViewById(R.id.listview);

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //初始化数据库
        mStudentDb = StudentDb.getInstance(getActivity());
        //初始化适配器
        mListAdapter = new MyListAdapter();
        //设置适配器
        listview.setAdapter(mListAdapter);
        //设置数据
        mListAdapter.setStudentList(mStudentDb.queryListStudent());

        //listview点击事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), EditStudentInfoActivity.class);
                StudentInfo studentInfo = mListAdapter.getItem(position);
                intent.putExtra("studentInfo", studentInfo);
                startActivityForResult(intent, 1000);
            }
        });


        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                StudentInfo item = mListAdapter.getItem(i);
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("操作");
                builder.setSingleChoiceItems(new String[]{"拨打电话", "删除"}, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        currentIndex = which;
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (currentIndex == 0) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + item.getMobile()));
                            startActivity(intent);

                        } else {
                            mStudentDb.delete(item.get_id());
                            Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                            //刷新数据
                            mListAdapter.setStudentList(mStudentDb.queryListStudent());
                        }


                        currentIndex = 0;
                    }
                });
                builder.show();

                return true;
            }
        });

        //新建
        rootView.findViewById(R.id.create).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), AddStudentInfoActivity.class), 1000);
            }
        });

        //点击音乐播放
        rootView.findViewById(R.id.music).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MusicActivity.class));
            }
        });
    }

    public class MyListAdapter extends BaseAdapter {
        private List<StudentInfo> mStudentInfoList = new ArrayList<>();

        public void setStudentList(List<StudentInfo> studentInfoList) {
            mStudentInfoList = studentInfoList;
            notifyDataSetChanged();
        }

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

        @Override
        public StudentInfo getItem(int i) {
            return mStudentInfoList.get(i);
        }

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            //加载布局文件
            View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item, null);
            //初始化控件
            TextView username = rootView.findViewById(R.id.username);
            TextView mobile = rootView.findViewById(R.id.mobile);
            TextView class_name = rootView.findViewById(R.id.class_name);
            TextView first_letter = rootView.findViewById(R.id.first_letter);
            //绑定数据
            StudentInfo studentInfo = getItem(i);
            username.setText(studentInfo.getUsername());
            mobile.setText(studentInfo.getMobile());
            class_name.setText(studentInfo.getClass_name());
            //取名字的第一个字显示
            String letter = studentInfo.getUsername().substring(0, 1);
            first_letter.setText(letter);

            // 创建Random类的实例
            Random random = new Random();
            // 生成1-4之间的随机数
            int randomNumber = random.nextInt(4) + 1;
            if (randomNumber == 1) {
                first_letter.setBackgroundColor(Color.parseColor("#ff6161"));
            } else if (randomNumber == 2) {
                first_letter.setBackgroundColor(Color.parseColor("#00cee5"));
            } else if (randomNumber == 3) {
                first_letter.setBackgroundColor(Color.parseColor("#ffb120"));
            } else {
                first_letter.setBackgroundColor(Color.parseColor("#7484fc"));
            }

            return rootView;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000) {
            //刷新数据
            mListAdapter.setStudentList(mStudentDb.queryListStudent());
        }
    }
}
  1. onActivityResult这个方法的实现,是处理在编辑通讯之后,回来需要及时刷新列表数据
  2. HomeFragment就是BottomNavigationView底部导航栏的首页

6. 效果图

在这里插入图片描述

7. 其它资料学习

1. Androidstudio底部导航栏实现: https://www.bilibili.com/video/BV1XB4y1d7et/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8

标签:int,rootView,Androidstudio,通讯录,letter,Override,new,ListView,public
From: https://blog.csdn.net/jky_yihuangxing/article/details/140919737

相关文章

  • Androidstudio开发,购物商城app 实现商品详情页(六)
    文章目录1.涉及到的技术点2.代码实现过程3.运行效果图4.参考学习文章相关视频教程在某站上面(......
  • Androidstudio开发,购物商城app实现主页底部导航栏(四)
    相关视频教程在某站上面(......
  • Androidstudio开发,购物商城app实现商品分类列表(五)
    相关视频教程在某站上面(......
  • Android ListView 详解
    AndroidListView详解介绍“Listview”是一种用户界面设计中的布局方式,它通过列表的形式展示信息,是一种将信息组织为条目(通常是行)的视图形式,每一项条目都是列表中的一行,可能包含文本、图像或其他元素。基本使用xml<?xmlversion="1.0"encoding="utf-8"?><RelativeLayout......
  • AndroidStudio 开发环境搭建
    文章目录AndroidStudio开发环境搭建JDK下载与安装,配置环境变量JDK1.8下载安装配置环境变量新建JAVA_HOME编辑Path下载AndroidStudio最新版本历史版本先安装JDK,后启动AS以管理员身份运行打开解决双击打不开的问题Error:你的主机中的软件中止了一个已建立的连接(或如下......
  • C++学习笔记(03)——通讯录管理系统设计
    记录一下利用C++来实现一个通讯录管理系统系统中需要实现的功能如下:添加联系人:向通讯录中添加新人,信息包括(姓名、性别、年龄、联系电话、家庭住址)最多记录1000人显示联系人:显示通讯录中所有联系人信息删除联系人:按照姓名进行删除指定联系人查找联系人:按照姓名查看指定联系人......
  • 【简单易懂,复制可运行】C++通讯录管理系统实现增删改查
    自己写的300行c++通讯录管理系统,可以实现如下功能: 具体代码如下:#include<iostream>usingnamespacestd;#defineMax1000//不要分号//设计联系人结构体structPerson{ stringm_Name; intm_Sex; intm_Age; stringm_Phone; stringm_Addr; };//设计......
  • 通讯录管理系统(C++基础知识实现)
    通讯录管理系统描述:本人C++小白一枚,正在学习C++基础知识,给大家分享一款使用C++基础知识实现的通讯录管理系统,一起努力进步,大佬轻点喷。1.知识点(1)预处理器指令(#include,#define);(2)命名空间使用(usingnamespacestd;);(3)函数定义:定义了多个函数,如menu,addContact,show......
  • 【Android】ListView和RecyclerView知识总结
    文章目录ListView步骤适配器AdpterArrayAdapterSimpleAdapterBaseAdpter效率问题RecyclerView具体实现不同布局形式的设置横向滚动瀑布流网格点击事件ListViewListView是Android中的一种视图组件,用于显示可滚动的垂直列表。每个列表项都是一个视图对象,ListVie......
  • 【ProtoBuf】通讯录实现(网络版)
    Protobuf还常用于通讯协议、服务端数据交换场景。那么在这个示例中,我们将实现一个网络版本的通讯录,模拟实现客户端与服务端的交互,通过Protobuf来实现各端之间的协议序列化。需求如下:客户端可以选择对通讯录进行以下操作:新增⼀个联系人删除⼀个联系人查询通讯录列表查......