I want items to change color when the user selects them. But when an item changes color, another item changes in the same way, I don't know why this error occurs, this is the code
I am using a listview and a simpleCursorAdapter, with a LoaderManager
class MainActivity : AppCompatActivity(), LoaderManager.LoaderCallbacks<Cursor>,AdapterView.OnItemClickListener{ var cols=listOf<String>( ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY ).toTypedArray() lateinit var listView1:ListView lateinit var adapter:SimpleCursorAdapter lateinit var cursor:Cursor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding=ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) if(ActivityCompat.checkSelfPermission(this, permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this,Array(1){ Manifest.permission.READ_CONTACTS},111) }else { var from=listOf<String>(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ).toTypedArray() var to = intArrayOf(R.id.name) adapter = SimpleCursorAdapter(this, R.layout.list_item_contacts, null, from, to,0) listView1=findViewById<ListView>(R.id.listView1) as ListView LoaderManager.getInstance(this).initLoader(1, null, this) } listView1.onItemClickListener=this } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if(requestCode==111 && grantResults[0]==PackageManager.PERMISSION_GRANTED){ LoaderManager.getInstance(this).initLoader(1,null,this) } } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { return CursorLoader(applicationContext, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, cols, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME ) } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) { adapter.swapCursor(data) listView1.adapter=adapter } override fun onLoaderReset(loader: Loader<Cursor>) { adapter.swapCursor(null) listView1.adapter=adapter } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { parent?.get(position)?.setBackgroundColor(Color.argb(96,189,189,189)) } }
And this is the resultenter image description here
example: when pressing the name of "angela" the name of "center of attention" is marked
I do not know if there is any other function that I do not know, it should be noted that I am starting in Android programming, if you could help me
https://stackoverflow.com/questions/67386064/setbackgroundcolor-error-in-the-onitemclicklistener May 04, 2021 at 09:45PM
没有评论:
发表评论