(原创)安卓在fragment里使用自定义ListView

发布时间 2023-12-23 22:05:56作者: lmj625

原创声明:本文所有图片和代码皆由本人制作和编写。

前言

在网上找了很久,如何在fragment里使用自定义的ListView,但是出现了各种Bug。甚至还有的人直接就下结论,没法这样用,必须要使用ListFragment。但是在我的一次次debug后,终于实现了。

故在此简练地记下这种方法。



4步走

第零:准备好你的ListItem布局

即,你要为想展示的每个小项目做个模板。
例如我的模板是这样的:
image


第一:在布局文件添加ListView组件

哪个fragment需要ListView组件就在该fragment的.xml布局文件添加如下代码:

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

第二:创建适配器

新建一个类,继承自ArrayAdapter<你自己提供数据的类>

实现构造器(在这里提供数据)

public TodayListAdapter(@NonNull Context context, int resource, List<Task> tasks) {
        //一定要记住在这里给父类构造器传入数据集合 不然什么都显示不出来
		super(context, resource,tasks);
        this.tasks = tasks;
        this.resourceId = resource;
    }

实现getView(在这里绑定布局)

@NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // 获取当前的任务项
        Task task = getItem(position);
        //实例化一个布局 在这里绑定你的小项目模板
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.today_list_item, parent,false);
	//修改信息
        TextView textViewTaskName = convertView.findViewById(R.id.taskName_todayitem_textView);
        TextView textViewTaskFrequency = convertView.findViewById(R.id.taskFre_todayitem_textView);

        if (task != null) {
            textViewTaskName.setText(task.getTaskName());
            textViewTaskFrequency.setText(task.getCurrentNum() + "/" + task.getFrequency());
        }
        return convertView;
    }

第三: 把第一步的xml文件里的ListView和第二步的适配器联系起来

打开你的fragment java代码

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
	//选用你写的fragment 布局
        View rootView = inflater.inflate(R.layout.fragment_today, container, false);

        // 绑定 你在第一步fragment 布局里的listView组件的id
        listView = rootView.findViewById(R.id.today_listView);

        // 初始化自定义适配器
        TodayListAdapter taskAdapter = new TodayListAdapter(requireContext(), R.layout.today_list_item, tasks);

        //绑定
        listView.setAdapter(taskAdapter);
        taskAdapter.notifyDataSetChanged();

        return rootView;
    }

第四:为每个小条目添加点击事件监听器

我是在适配器的getView方法写的。示例:

Button clockIn_btn = convertView.findViewById(R.id.clockIn_todayitem_btn);
        //打卡按钮事件监听器
        clockIn_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(task.getCurrentNum() < task.getFrequency()){
                    //TODO:更新统计表
                    //这一次做完
                    task.setCurrentNum(task.getCurrentNum() + 1);
                    if(task.getCurrentNum() == task.getFrequency()){
                        // 获取当前日期
                        Toast.makeText(getContext(), "执行统计表插入", Toast.LENGTH_SHORT).show();
                        Date currentDate = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate = sdf.format(currentDate);
                        myDataHelper.insertStatistic(task.getTaskName(),formattedDate);
                    }
                    myDataHelper.updateCurrentNum(task.getTaskName(),task.getCurrentNum());
                    textViewTaskFrequency.setText( task.getCurrentNum() + "/" + task.getFrequency());
                }else{
                    //Toast.makeText(getContext(), "今日已经完成咯~", Toast.LENGTH_SHORT).show();
                }
            }
        });


后记

感谢你看到这里。