我的列表视图上的“删除"按钮无法正常工作 [英] Delete button on my listview is not working as it is supposed to

查看:50
本文介绍了我的列表视图上的“删除"按钮无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想在列表的每个项目上都有一个删除按钮,以便当按下该按钮时,我希望该特定列表项目被完全删除.但是,当我尝试执行此操作时,它不起作用.此外,如果我单击删除图标两次,该应用程序将崩溃.这是我的列表适配器的代码:

so I was wanting to have a delete button on each item of my list, so that when that button is pressed, I want that particular list item to be completely removed. However, when I try to do this, it doesn't work. Moreover, If I click on the delete icon twice, the app crashes. This is the code for my list adapter :

    package com.example.taskmasterv3;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

public class SubtaskAdapter extends ArrayAdapter<subtask> {


    private final Context context;
    private ArrayList<subtask> values;


    public SubtaskAdapter(Context context, ArrayList<subtask> list) {

        //since your are using custom view,pass zero and inflate the custom view by overriding getview
    super(context, 0 , list);
    this.context = context;
    this.values = list;
}



@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    //check if its null, if so inflate it, else simply reuse it
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.subtask_item, parent, false);
    }

    //use convertView to refer the childviews to populate it with data
    TextView tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
    ImageView ivPri = convertView.findViewById(R.id.ivPri);
    ImageView ivTime = convertView.findViewById(R.id.ivTime);
    ImageView ivDelete = convertView.findViewById(R.id.ivDelete);

    tvSubtaskName.setText(values.get(position).getSubtaskName());

    if (values.get(position).isPriHigh()) {
        ivPri.setImageResource(R.drawable.priority_high);
    } else if (values.get(position).isPriMed()) {
        ivPri.setImageResource(R.drawable.priority_med);
    } else if (values.get(position).isPriLow()) {
        ivPri.setImageResource(R.drawable.priority_low);
    }

    if (values.get(position).isTimeMore()) {
        ivTime.setImageResource(R.drawable.time_symbol_more);
    } else if (values.get(position).isTimeMed()) {
        ivTime.setImageResource(R.drawable.time_symbol_med);
    } else if (values.get(position).isTimeLess()) {
        ivTime.setImageResource(R.drawable.time_symbol_less);
    }


    // Delete button for subtasks (NOT WORKING)

    ivDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            values.remove(position);
            notifyDataSetChanged();
        }
    });

    //return the view you inflated
    return convertView;
}





//to keep adding the new subtasks try the following
public void addANewSubTask(subtask newSubTask){
    ArrayList<subtask> newvalues = new ArrayList<>(this.values);
    newvalues.add(newSubTask);
    this.values = newvalues;
    notifyDataSetChanged();

}

}

推荐答案

由于继续创建OnClickListener并使用findViewById()解析视图ID,以这种方式使用ListView非常糟糕并且占用大量内存.侵入性较小的解决方案是使用可缓存所有View ID和ClickListener的ViewHolder:

Using ListView in this way is very bad and memory heavy due to continue creation of OnClickListener and resolving View IDs using findViewById(). The less invasive solution is to use a ViewHolder that caches all View IDs and the ClickListener:

public class SubtaskAdapter extends ArrayAdapter<subtask> {

    private final LayoutInflater mLayoutInflater;

    public SubtaskAdapter(@NonNull final Context context, @NonNull final List<subtask> values) {
        super(context, R.layout.subtask_item, values);
        this.mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    private static class ViewHolder {
        private int mPosition = -1;
        private final TextView tvSubtaskName;
        private final ImageView ivPri;
        private final ImageView ivTime;
        private final ImageView ivDelete;
        private final View.OnClickListener mOnClickListener;
        private ViewHolder(@NonNull final ArrayAdapter<subtask> arrayAdapter, @NonNull final View convertView) {
            this.tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
            this.ivPri = convertView.findViewById(R.id.ivPri);
            this.ivTime = convertView.findViewById(R.id.ivTime);
            this.ivDelete = convertView.findViewById(R.id.ivDelete);
            this.mOnClickListener = new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    arrayAdapter.remove(arrayAdapter.getItem(ViewHolder.this.mPosition));
                    arrayAdapter.notifyDataSetChanged();
                }
            };
            this.ivDelete.setOnClickListener(this.mOnClickListener);
        }
        private void setPosition(final int position) { this.mPosition = position; }
    }

    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull final ViewGroup parent) {
        final View cParentView = super.getView(position, convertView, parent);
        if (cParentView != null) return cParentView;
        ViewHolder holder;

        if (convertView == null) {
            convertView = this.mLayoutInflater.inflate(R.layout.subtask_item, parent, false);
            holder = new ViewHolder(this, convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.setPosition(position);
        
        final subtask cCurrentSubtask = getItem(position);

        holder.tvSubtaskName.setText(cCurrentSubtask.getSubtaskName());

        if (cCurrentSubtask.isPriHigh()) {
            holder.ivPri.setImageResource(R.drawable.priority_high);
        } else if (cCurrentSubtask.isPriMed()) {
            holder.ivPri.setImageResource(R.drawable.priority_med);
        } else if (cCurrentSubtask.isPriLow()) {
            holder.ivPri.setImageResource(R.drawable.priority_low);
        }

        if (cCurrentSubtask.isTimeMore()) {
            holder.ivTime.setImageResource(R.drawable.time_symbol_more);
        } else if (cCurrentSubtask.isTimeMed()) {
            holder.ivTime.setImageResource(R.drawable.time_symbol_med);
        } else if (cCurrentSubtask.isTimeLess()) {
            holder.ivTime.setImageResource(R.drawable.time_symbol_less);
        }
        
        return convertView;
    }
}

您不需要使用内部的值"要保存所有项目,您可以使用"ArrayAdapter.add()"创建传递初始项Array/List的ArrayAdapter之后,以及其他类似方法(remove(),getItem(),getCount()等).

You do not need to use an internal "values" to hold all Items, you can use "ArrayAdapter.add()" and other similar methods (remove(), getItem(), getCount(), etc..) after you created the ArrayAdapter passing initial Items Array/List.

编辑:要将项目添加到ArrayAdapter,您需要保存ArrayAdapter实例,然后在其实例中调用其"add()".方法.

EDIT: To add items to the ArrayAdapter you need to save ArrayAdapter instance and then call its "add()" method.

public class MainActivity extends Activity {
    ...
    @Nullable
    private SubtaskAdapter mSubtaskAdapter = null;
    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSubtaskAdapter = new SubtaskAdapter(this, subtask_items);
    }
    private boolean addSubtaskToList(@Nullable final subtask newSubtask) {
        if ((mSubtaskAdapter == null) || (newSubtask == null)) return false;
        mSubtaskAdapter.add(newSubtask);
        return true;
    }
}

这篇关于我的列表视图上的“删除"按钮无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆