安卓 使用listView,实现长按删除

 

 

 

 

结果图:

实现一个内部类 (适配器)

selectMode为bool变量 分别表示选中模式和未选中模式。

 

package com.example.study;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {
    private Button search;
    private Button mBtn;
    private ListView mListView;
    private Button rank_by_name,cancel,delete;
    private boolean  selectMode=false;

    int index;
    MyAdapter adapter;
    Drawable []a=new Drawable[4];
    ArrayList<student> students=new ArrayList<student>();
    public class MyListItem{
        public student data;
        public boolean checked=false;
    }
    public class MyAdapter extends BaseAdapter {
        Drawable selected,unselected;
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public MyAdapter(){
            selected=getDrawable(R.drawable.ic_checked);
            unselected=getDrawable(R.drawable.ic_unchecked);
        }
        ArrayList<MyListItem> temp=new ArrayList<MyListItem>();




        @Override
        public int getCount() {                  // 获取有多少行
            return temp.size();
        }

        @Override
        public Object getItem(int position) {    //获取某一行
            return temp.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {              // 获取某一行的显示


            if(convertView==null)
//                textView=new TextView(MainActivity.this);
                convertView=getLayoutInflater().inflate(R.layout.list_view_item,parent,false);
            MyListItem Selected=(MyListItem)getItem(position);
            student data=Selected.data;

            TextView name=(TextView)convertView.findViewById(R.id.name);
            TextView age=(TextView)convertView.findViewById(R.id.age);
            TextView home=(TextView)convertView.findViewById(R.id.home);




            name.setText(data.name);
            age.setText(data.age);
            home.setText(data.home);
               //convertView 这个曾经忘写了 bug半小时
            ImageView check = (ImageView)convertView.findViewById(R.id.select_checked);

            if(selectMode)
            {
                check.setVisibility(View.VISIBLE);
            }
            else
            {
                check.setVisibility(View.GONE);
            }

            if(Selected.checked)
                check.setImageDrawable(selected);
            else
                check.setImageDrawable(unselected);
            return convertView;
        }
    }
    public void Select_or_Unselect(){
        ImageView check=(ImageView)findViewById(R.id.select_checked);
//            Log.d("imageview",String.valueOf(selectMode));
        if(selectMode){
            check.setVisibility(View.VISIBLE);
        }
        else{
            check.setVisibility(View.GONE);
        }
    }

    public void showAll(){
        adapter.temp.clear();
        for(student s:students){
            MyListItem item=new MyListItem();
            item.data=s;
            item.checked=false;
            adapter.temp.add(item);

        }
        adapter.notifyDataSetChanged();
    }
    public void goSelectMode (boolean yes)
    {
        // 在进入选择模式时,显示上边的操作按钮
        // 退出选择模式时,隐藏上边的操作按钮
        View layout = findViewById(R.id.select_bar);
        if(yes )
        {
            layout.setVisibility(View.VISIBLE); // 显示
//            Select_or_Unselect();
        }
        else
        {
            layout.setVisibility(View.GONE); // 隐藏
//            Select_or_Unselect();
        }

        // 列表项里要不要显示选择框
        this.selectMode = yes;
        this.adapter.notifyDataSetChanged();

    }
    public void onSelectCancel(View view)
    {
        // 因为已经退出选择模式,所以把checked都置为false
        for(MyListItem item: adapter.temp)
        {
            item.checked = false;
        }
        goSelectMode(false);
    }
//    public void RankByName(){
//        adapter.temp.clear();
//        adapter.temp.addAll(students);
//        Collections.sort(adapter.temp, new Comparator<student>() {
//            @Override
//            public int compare(student o1, student o2) {
//                return o1.name.compareTo(o2.name);
//            }
//        });
//        adapter.notifyDataSetChanged();
//    }
//    public void showFilter(View view){
//        EditText edit=findViewById(R.id.ed_search);
//        String filter=edit.getText().toString().trim();
//        edit.clearFocus();
//        hideKeyWord();
//        adapter.temp.clear();
//        for( student s:students){
//            if(s.name.indexOf(filter)>=0){
//                adapter.temp.add(s);
//            }
//        }
//        adapter.notifyDataSetChanged();
//    }
// 删除选中的项
    public void onSelectDelete(View view)
    {
        // 使用迭代器,遍历删除多项
        Iterator<MyListItem> iter = adapter.temp.iterator();
        while(iter.hasNext())
        {
            MyListItem item = iter.next();
            if(item.checked)
            {
                // 从listAdapter.result中删除
                iter.remove();

                // 从dataSource中删除
                students.remove(item.data);
            }
        }

        // 通知界面更新
        adapter.notifyDataSetChanged();
    }
    public void hideKeyWord(){
        InputMethodManager im=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),0);
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        students.add(new student("mao","21","henan1"));
        students.add(new student("li","22","zhejiang"));
        students.add(new student("wang","23","shanghai"));
        students.add(new student("li 123","22","zhejiang"));
        students.add(new student("wang","23","shanghai"));
        students.add(new student("li hai","22","zhejiang"));
        students.add(new student("wang fang","23","shanghai"));

        a[0]=getDrawable(R.drawable.im01);
        a[1]=getDrawable(R.drawable.im02);
        a[2]=getDrawable(R.drawable.im03);
        a[3]=getDrawable(R.drawable.im04);
        mListView=findViewById(R.id.ListView);
        rank_by_name=findViewById(R.id.rank_by_name);
        delete=findViewById(R.id.delete_select);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSelectDelete(v);
            }
        });
        cancel=findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSelectCancel(v);
            }
        });
//        rank_by_name.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                RankByName();
//            }
//        });
//        search=findViewById(R.id.search);
//        search.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showFilter(v);
//
//            }
//        });
        adapter=new MyAdapter();
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MyListItem item = (MyListItem)adapter.getItem(position);
                if(selectMode)
                {
                    item.checked = ! item.checked; // 反选
                    adapter.notifyDataSetChanged();
                }
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                student s= (student) adapter.getItem(position);
//                Toast.makeText(MainActivity.this,s.name+"这项被点击了",Toast.LENGTH_SHORT).show();
//                goSelectMode(true);

                MyListItem item = (MyListItem)adapter.getItem(position);
                item.checked = true; // 反选
                goSelectMode (true);
                return true;
            }
        });


        showAll();
        goSelectMode (false);
        mBtn=findViewById(R.id.button_next);
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                display();
            }
        });
    }
    public void ItemLongClick(int p){

    }


    public void display(){
        index+=1;
        if(index>3){
            index=index%4;
        }
        ImageView imageView=findViewById(R.id.imageView);
        imageView.setImageDrawable(a[index]);
    }
}

 .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=".MainActivity">


    <Button
        android:id="@+id/button_next"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下一张" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"


        app:srcCompat="@drawable/im01"

        tools:visibility="visible" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        >
        <EditText
            android:layout_width="10dp"
            android:id="@+id/ed_search"
            android:layout_weight="1"


            android:layout_height="match_parent">

        </EditText>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/search"
            android:text="搜索"
            android:textSize="25sp"
            >

        </Button>
    </LinearLayout>

    <Button
        android:id="@+id/rank_by_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按名字排序" />

    <ListView
        android:id="@+id/ListView"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="0dp"
        >

    </ListView>



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/select_bar"

        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/delete_select"
            android:layout_marginLeft="50dp"
            android:text="删除所选"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="150dp"
            android:id="@+id/cancel"
            android:text="取消"
            >

        </Button>

    </LinearLayout>
</LinearLayout>
<?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">

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Text"
        android:textSize="25sp" />
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:textSize="25sp"
        android:text="text"
        android:gravity="center"
        android:id="@+id/age"
        >

    </TextView>
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:id="@+id/home"
        android:textSize="25sp"
        android:text="text"
        android:gravity="center"
        android:layout_weight="1"
        >

    </TextView>
    <ImageView
        android:layout_width="30dp"
        android:layout_height="48dp"
        android:scaleType="fitCenter"
        android:src="@drawable/unselected"
        android:id="@+id/select_checked"

        >

    </ImageView>
</LinearLayout>

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值