2017-11-17 8 views
1

모든 사용자의 연락처와 관련 전화 번호가있는 목록보기가 있습니다. 사용자가 여러 셀/행을 선택할 수있게하고 목록에서 선택 연락처를 강조 표시하여 사용자가 상태를 잃지 않도록해야합니다.선택한 경우 안드로이드 목록보기에서 여러 항목 강조 표시

다음과 같은 사용자 지정 어댑터 설치가 있습니다.

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 
    } 

} 

이 선택한 연락처에 hightlight 지금까지 내 최고의 솔루션하지만 문제는 스크롤 할 때 연락처의 나머지 부분에 대한 배경을 설정하는 데 실패한다는 것입니다.

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()) 

     } 
    }) 

이 시점에서 도움을 받으실 수 있습니다.

답변

0

가 어댑터에

var isSelected=false 

추가 홀더에 부울에 isSelected 필드를 추가

view.selected=true 

longClickListener

에 추가

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