选中时,在android列表视图中高亮显示多个项目

选中时,在android列表视图中高亮显示多个项目,android,listview,android-studio,kotlin,contacts,Android,Listview,Android Studio,Kotlin,Contacts,我有一个包含所有用户联系人及其相关电话号码的列表视图。我希望他们能够选择多个单元格/行,然后列表必须突出显示select contacts,以便用户不会丢失状态 我有一个自定义适配器设置,如下所示 public class ContactsListAdapter extends BaseAdapter { private static final String TAG = "ContactsListAdapter"; /*********** Declare Used Var

我有一个包含所有用户联系人及其相关电话号码的列表视图。我希望他们能够选择多个单元格/行,然后列表必须突出显示select contacts,以便用户不会丢失状态

我有一个自定义适配器设置,如下所示

public class ContactsListAdapter extends BaseAdapter {

    private static final String TAG = "ContactsListAdapter";

    /*********** Declare Used Variables *********/
    private Activity activity;
    private ArrayList data;
    private static LayoutInflater inflater=null;
    public Resources res;
    ContactsModel tempValues=null;
    int i=0;

    public ContactsListAdapter(Activity a, ArrayList d, Resources resLocal) {

        /********** Take passed values **********/
        activity = a;
        data=d;
        res = resLocal;

        /***********  Layout inflator to call external xml layout () ***********/
        inflater = ( LayoutInflater )activity.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        if (data != null) {
            if(data.size()<=0)
                return 1;
            return data.size();
        } else
            return 0;
    }

    @Override
    public Object getItem(int position) {
        if (data != null)
            return position;
        return null;
    }

    @Override
    public long getItemId(int position) {
        if (data != null)
            return position;
        return 0;
    }

    /********* Create a holder Class to contain inflated xml file elements *********/
    public static class ViewHolder{

        public RelativeLayout containerView;
        public TextView fullname;
        public TextView phone_number;

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        View vi = convertView;
        final ContactsListAdapter.ViewHolder holder;

        if(convertView==null){

            /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
            vi = inflater.inflate(R.layout.contacts_list_item, null);

            /****** View Holder Object to contain tabitem.xml file elements ******/

            holder = new ContactsListAdapter.ViewHolder();
            holder.fullname = vi.findViewById(R.id.contactName);
            holder.phone_number = vi.findViewById(R.id.contactPhoneNumber);
            holder.containerView = vi.findViewById(R.id.containerView);

            /************  Set holder with LayoutInflater ************/
            vi.setTag( holder );
        }
        else
            holder=(ContactsListAdapter.ViewHolder)vi.getTag();

        if(data.size()<=0)
        {
            //holder.username.setText("No Data");

        }
        else
        {
            /***** Get each Model object from Arraylist ********/
            tempValues=null;
            tempValues = ( ContactsModel ) data.get( position );

            holder.fullname.setText(tempValues.getFullname());
            holder.phone_number.setText(tempValues.getPhone_number());

        }
        return vi;
    }

}
class Contacts(context: Context, listview : ListView, adapter : ContactsListAdapter?, CustomListViewValuesArr : ArrayList<ContactsModel>, progress : ProgressBar?) : AsyncTask<Unit, Unit, Unit>() {

    val context : Context = context
    var listview : ListView = listview
    var adapter : ContactsListAdapter? = adapter
    var CustomListViewValuesArr : ArrayList<ContactsModel> = CustomListViewValuesArr
    var holder : ArrayList<ContactsModel>? = null
    var progress : ProgressBar? = progress

    override fun onPreExecute() {
        super.onPreExecute()
        progress!!.visibility = View.VISIBLE
        progress!!.animate()
    }

    override fun doInBackground(vararg params: Unit?) {

        var obj : JSONObject = JSONObject()

        var contactsModels : ArrayList<ContactsModel> = arrayListOf()

        var cr : ContentResolver = context.contentResolver

        var cur : Cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null)

        if ((if(cur != null) cur.getCount() else 0) > 0) {
            while (cur != null && cur.moveToNext()) {
                val id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID))

                val name = cur.getString(cur.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME))

                if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {

                    val pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            arrayOf(id), null)

                    while (pCur.moveToNext()) {
                        var phoneNo : String = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER)).replace("\\D", "")

                        obj.put(name, phoneNo)

                        var model : ContactsModel = ContactsModel()
                        model.fullname = name
                        model.phone_number = phoneNo
                        contactsModels.add(model)
                    }

                    pCur.close()

                }
            }

            holder = contactsModels

        }

    }

    override fun onPostExecute(result: Unit?) {
        super.onPostExecute(result)

        CustomListViewValuesArr.clear()
        CustomListViewValuesArr.addAll(holder!!)
        //Log.d(TAG, "Adapter Notify")
        adapter!!.notifyDataSetChanged()

        progress!!.visibility = View.GONE
    }

}
公共类ContactsListAdapter扩展了BaseAdapter{
私有静态最终字符串标记=“ContactsListAdapter”;
/***********声明使用的变量*********/
私人活动;
私有数组列表数据;
专用静态充气机=空;
公共资源;
ContactsModel tempValues=null;
int i=0;
公共联系人静态适配器(活动a、阵列列表d、资源本地){
/**********接受传递的值**********/
活动=a;
数据=d;
res=resLocal;
/***********布局充气器调用外部xml布局()***********/
充气器=(充气器)活动。
getSystemService(上下文布局\充气机\服务);
}
@凌驾
public int getCount(){
如果(数据!=null){
if(data.size()0){
val pCur=cr.query(
ContactsContract.CommonDataTypes.Phone.CONTENT\u URI,null,
ContactsContract.CommonDataTypes.Phone.CONTACT_ID+“=?”,
arrayOf(id),null)
while(pCur.moveToNext()){
var phoneNo:String=pCur.getString(pCur.getColumnIndex(
contacts contract.commonDataTypes.Phone.NUMBER)。替换(“\\D”,”)
obj.put(姓名、电话号码)
变量模型:ContactsModel=ContactsModel()
model.fullname=名称
model.phone_number=电话号码
contactsModels.add(模型)
}
pCur.close()
}
}
保持架=触点模型
}
}
重写onPostExecute(结果:单位?){
super.onPostExecute(结果)
CustomListViewValuesArr.clear()
CustomListViewValuesArr.addAll(持有者!!)
//Log.d(标记“适配器通知”)
适配器!!.notifyDataSetChanged()
进度!!.visibility=View.GONE
}
}
这是到目前为止我最好的解决方案,可以高亮显示选定的联系人,但问题是当您滚动时,它无法为其余联系人设置背景

contactsListView!!.setOnItemClickListener(object : AdapterView.OnItemClickListener {
        override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val items = contactsListView!!.getCheckedItemPositions()

            for (i in 0 until contactsListView!!.getAdapter().getCount()) {

                if (items.get(i) == true) {

                    parent!!.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.hapningGrey))
                    val contactName = parent.getChildAt(i).findViewById<TextView>(R.id.contactName)
                    val phoneNumber = parent.getChildAt(i).findViewById<TextView>(R.id.contactPhoneNumber)

                    var itemPhoneNumber : String = phoneNumber.text.toString()
                            .replace("(", "")
                            .replace(")", "")
                            .replace(" ", "")
                            .replace("-", "")

                    if (nominatedList.contains(itemPhoneNumber) == false) {
                        nominatedList.add(itemPhoneNumber)
                    }

                } else {

                    parent!!.getChildAt(i).setBackgroundColor(Color.TRANSPARENT)
                    val contactName = parent.getChildAt(i).findViewById<TextView>(R.id.contactName)
                    val phoneNumber = parent.getChildAt(i).findViewById<TextView>(R.id.contactPhoneNumber)

                    var itemPhoneNumber : String = phoneNumber.text.toString()
                            .replace("(", "")
                            .replace(")", "")
                            .replace(" ", "")
                            .replace("-", "")

                    if (nominatedList.contains(itemPhoneNumber) == true) {
                        nominatedList.remove(itemPhoneNumber)
                    }

                }


            }

            Log.d(TAG, nominatedList.toString())

        }
    })
contactsListView!!。setOnItemClickListener(对象:AdapterView.OnItemClickListener{
重写MClick(父项:AdapterView?,视图:view?,位置:Int,id:Long){
val items=contactsListView!!.getCheckedItemPositions()
对于(0中的i,直到contactsListView!!.getAdapter().getCount()){
if(items.get(i)=true){
parent!!.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.hapinggrey))
val contactName=parent.getChildAt(i).findViewById(R.id.contactName)
val phoneNumber=parent.getChildAt(i).findViewById(R.id.contactPhoneNumber)
var itemPhoneNumber:String=phoneNumber.text.toString()
.替换(“(”,“”)
.替换(“)”,“”)
.替换(“,”)
.替换(“-”,“”)
if(nominatedList.contains(itemPhoneNumber)==false){
命名列表。添加(itemPhoneNumber)
}
}否则{
父!!.getChildAt(i).setBackgroundColor(颜色.透明)
val contactName=parent.getChildAt(i).findViewById(R.id.contactName)
val phoneNumber=parent.getChildAt(i).findViewById(R.id.contactPhoneNumber)
var itemPhoneNumber:String=phoneNumber.text.toString()
.替换(“(”,“”)
.替换(“)”,“”)
.替换(“,”)
.替换(“-”,“”)
if(nominatedList.contains(itemPhoneNumber)==true){
nominatedList.remove(itemPhoneNumber)
}
}
}
Log.d(标记,nominatedList.toString())
}
})

如果您有任何帮助,我们将不胜感激。

添加到longClickListener

view.selected=true
将isSelected字段添加为布尔值

var isSelected=false
添加到适配器

holder.isSelected=vi.isSelected
if (holder.isSelected)
  vi.background=ContextCompat.getColor(vi.context,R.color.blue)

添加到longClickListener

view.selected=true
将isSelected字段添加为布尔值

var isSelected=false
添加到适配器

holder.isSelected=vi.isSelected
if (holder.isSelected)
  vi.background=ContextCompat.getColor(vi.context,R.color.blue)