How to call canvas from another function? - kotlin

I am struggling with this problem
I have for example this code
val itemSwipe = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT), DialogFragmentNoticias.DialogFragmentDismissListener {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
super.onChildDraw(c, recyclerView, viewHolder, 0f, dY, actionState, isCurrentlyActive);
}
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
}
override fun DialogNoticiasDismiss() {
viewHol?.let {
adapter.notifyItemChanged(it)
allowed = true
}
}
}
I have extended an interface to make a listener, and what I am looking for is use the parameters like c:Canvas or viewHolder:RecyclerView.ViewHolder
in this function listener
override fun DialogNoticiasDismiss() {
viewHol?.let {
adapter.notifyItemChanged(it)
allowed = true
}
}
How do I manage to do this? Any ideas will help a lot
Thank you in advance

Related

Problem with recyclerview last item added not showed inside a fragment

I having problem showing the last item when I update my recyclerview. The data is correct but I have to scroll down to show the last item because is out of screen. It's not a problem about constraint, nor margins, I've double checked it.I've read several posts here about how to fix it but none has worked for my code so far. Any suggestions?
This is my adapter:
class ComentarioAdaptador(private var context: Context, private var publicacionLista: ArrayList<Comentario>): RecyclerView.Adapter<ComentarioAdaptador.ViewHolder>()
{
private var tipoUsuario=""
class ViewHolder( itemView: View):RecyclerView.ViewHolder(itemView) {
var ivPerfil : ImageView = itemView.findViewById(R.id.iv_perfil)
var tvNombreUsuario: TextView = itemView.findViewById(R.id.tv_propietario)
var tvComentario: TextView = itemView.findViewById(R.id.tv_comentario)
var tvFecha: TextView = itemView.findViewById(R.id.tv_fecha)
var btnBorrar: Button =itemView.findViewById(R.id.brn_borrar_comentario)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =LayoutInflater.from(context).inflate(R.layout.comentario,parent,false)
determinarTipoUsuario()
return ViewHolder(view)
}
override fun getItemCount(): Int {
return publicacionLista.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val comentario = publicacionLista[position]
holder.tvComentario.text =comentario.contenido
holder.tvFecha.text= comentario.fecha
buscarUsuario(holder.ivPerfil, holder.tvNombreUsuario, comentario.creadoPor,holder.btnBorrar)
holder.btnBorrar.setOnClickListener{
}
}
private fun buscarUsuario(ivPerfil: ImageView, tvNombreUsuario: TextView, propietario: String, btnBorrar:Button) {
val usuarioRef = FirebaseDatabase.getInstance().reference.child("Usuarios").child(propietario)
usuarioRef.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
val usuario=snapshot.getValue(Usuario::class.java)
tvNombreUsuario.text=usuario!!.usuario
Glide.with(context).load(usuario.perfil).circleCrop().into(ivPerfil)
if (tipoUsuario=="usuario")
btnBorrar.isGone=true
else
btnBorrar.isVisible=true
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun determinarTipoUsuario(){
val usuarioActual = FirebaseAuth.getInstance().currentUser!!
val userID = usuarioActual.uid
//LUEGO HAGO UNA INSTANCIA DE ESA UID
val busqueda = FirebaseDatabase.getInstance().getReference("Usuarios").child(userID)
//FINALMENTE LE PONGO UN LISTENER PARA GUARDAR DATOS
busqueda.addValueEventListener(object : ValueEventListener
{
override fun onDataChange(snapshot: DataSnapshot)
{
tipoUsuario = snapshot.getValue(Usuario::class.java)!!.tipo
Toast.makeText(context, tipoUsuario, Toast.LENGTH_SHORT).show()
}
override fun onCancelled(error: DatabaseError)
{}
})
}
}
This is how I call the the recyclerview on my fragment:
private fun mostrarComentarios(uidPostRecibido:String){
val comentariosRef= FirebaseDatabase.getInstance().reference.child("Comentarios").child(uidPostRecibido)
listaComentarios!!.clear()
comentariosRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (snapshot in snapshot.children)
{
val comentario = snapshot.getValue(Comentario::class.java)
listaComentarios!!.add(comentario!!)
}
comentarioAdaptador!!.notifyDataSetChanged()
}
}
override fun onCancelled(error: DatabaseError) {
}
}
)
}

How do I access the View object in a GestureDetector override in Kotlin?

I have a TextView with a GestureDetector attached like this:
interface GestureInterface {
fun setOnScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float)
fun onClick(e:MotionEvent)
}
class MyGestureDetector(private val gestureInterfacePar: GestureInterface) : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
gestureInterfacePar.onClick(e)
return false
}
override fun onLongPress(e: MotionEvent) {}
override fun onDoubleTap(e: MotionEvent): Boolean { return false }
override fun onDoubleTapEvent(e: MotionEvent): Boolean { return false }
override fun onSingleTapConfirmed(e: MotionEvent): Boolean { return false }
override fun onShowPress(e: MotionEvent) {}
override fun onDown(e: MotionEvent): Boolean { return true }
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
gestureInterfacePar.setOnScroll(e1, e2, distanceX, distanceY)
return false
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
return super.onFling(e1, e2, velocityX, velocityY)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
...
val mGestureDetector = GestureDetector(this, MyGestureDetector(object : GestureInterface {
override fun setOnScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float) {
//handle the scroll
}
override fun onClick(e: MotionEvent) {
//handle the single click
val tv = findViewById<TextView>(R.id.tvAnimalList)
val txt = tv.text
}
...
}))
...
I'm referencing the TextView that was clicked in my override implementation for onClick, with the line val tv = findViewById<TextView>(R.id.tvAnimalList), which I'd rather make more reusable by somehow referencing the TextView that was clicked via the e:MotionEvent argument, or something, but I can't see how to get at it.

Recyclerview item background color change

How can I change the background color of the selected item in RecyclerView Kotlin
Thank you from now
How to change the background color of only selected view in my recycle view example?only the background color of clicked itemview needs to be changed
OutTimeActiviyt
val linearLayoutManager = LinearLayoutManager(this)
layoutBnd.outRecylerView.layoutManager = linearLayoutManager
layoutBnd.outRecylerView.setHasFixedSize(false)
//IN RECYCLERVIEW
out_TimeList.clear()
val out_DataBase = this.openOrCreateDatabase("Park", Context.MODE_PRIVATE, null)
val recyclerCursor = out_DataBase.rawQuery("SELECT * FROM Money", null)
val listTimeIndex = recyclerCursor.getColumnIndex("MoneyListName")
while (recyclerCursor.moveToNext()) {
out_TimeList.add(recyclerCursor.getString(listTimeIndex))
}
recyclerCursor.close()
val recyclerMoneyListName = Out_Recyler_Adapter(out_TimeList)
layoutBnd.outRecylerView.adapter = recyclerMoneyListName
recyclerMoneyListName.setOnItemClickListener(object : Out_Recyler_Adapter.onItemClickListener{
override fun onItemClick(position: Int) {
Toast.makeText(this#OutTimeActivity, "Selected item:${position}", Toast.LENGTH_SHORT).show()
}
})
Out_TimeAdapter
class Out_Recyler_Adapter(private val out_TimeList: ArrayList<String>) :
RecyclerView.Adapter<Out_Recyler_Adapter.ViewHolder>() {
private lateinit var out_ClickListener: onItemClickListener
interface onItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener) {
out_ClickListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recyler_style, parent, false)
return ViewHolder(view, out_ClickListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val ItemsViewModel = out_TimeList[position]
holder.textView.text = ItemsViewModel
}
override fun getItemCount(): Int {
return out_TimeList.size
}
class ViewHolder(ItemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(ItemView) {
val textView: TextView = itemView.findViewById(R.id.style_txtParkingInfo)
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
}

swipeToDelete works but can't get icon to show up

I wanted my listitems to be swipeabel in order to delete them and I found this code through a video and it works for me if i comment out some stuff and dont't pass a context to the abstract class. now the thing is that I can't get the delete icon to work and the problem seems to be that by the time i call this abstract class i don't yet have usable context i can pass on.
abstract class SwipeToDeleteCallback(context: Context) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
private val deleteIcon = ContextCompat.getDrawable(context, R.drawable.ic_delete)
private val intrinsicWidth = deleteIcon!!.intrinsicHeight
private val intrinsicHeight = deleteIcon!!.intrinsicHeight
private val background = ColorDrawable()
private val backgroundColor = Color.parseColor("#f44336")
private val clearPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) }
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onChildDraw(
c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean
) {
val itemView = viewHolder.itemView
val itemHeight = itemView.bottom - itemView.top
val isCanceled = dX == 0f && !isCurrentlyActive
if (isCanceled) {
clearCanvas(c, itemView.right + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat())
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
return
}
// Draw the red delete background
background.color = backgroundColor
background.setBounds(itemView.right + dX.toInt(), itemView.top, itemView.right, itemView.bottom)
background.draw(c)
// Calculate position of delete icon
val deleteIconTop = itemView.top + (itemHeight - intrinsicHeight) / 2
val deleteIconMargin = (itemHeight - intrinsicHeight) / 2
val deleteIconLeft = itemView.right - deleteIconMargin - intrinsicWidth
val deleteIconRight = itemView.right - deleteIconMargin
val deleteIconBottom = deleteIconTop + intrinsicHeight
// Draw the delete icon
deleteIcon!!.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom)
deleteIcon.draw(c)
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
private fun clearCanvas(c: Canvas?, left: Float, top: Float, right: Float, bottom: Float) {
c?.drawRect(left, top, right, bottom, clearPaint)
}
}
This is the fragment i use that class in (i didn't put all the code in here because most of it has nothing to do with the question):
class HomeFragment : Fragment() {
private lateinit var adapter: ListAdapter
private lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
adapter = ListAdapter()
recyclerView = binding.recyclerView
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireActivity())
recyclerView.apply {
ItemTouchHelper(deleteSwipeHandler).attachToRecyclerView(this)
}
mItemViewModel = ViewModelProvider(this)[ItemViewModel::class.java]
mItemViewModel.fetchAllItems.observe(viewLifecycleOwner) { item ->
adapter.setData(item)
binding.tvHelp.isInvisible = adapter.itemCount > 0
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.fab.setOnClickListener {
if (ContextCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.CAMERA
) == PERMISSION_GRANTED
) {
intentAndFileProvider()
} else {
requestPermissions(arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_CODE)
}
}
}
private val deleteSwipeHandler = object : SwipeToDeleteCallback(context) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val pos = viewHolder.layoutPosition
val item = adapter.itemList[pos]
mItemViewModel.deleteItem(item)
Snackbar.make(requireView(), "Successfully deleted!", Snackbar.LENGTH_LONG).apply {
setAction("Undo") {
mItemViewModel.addItem(item)
}
}.show()
}
}
}
Pls help me out here! I appreciate every answer & comment!

I want to use recyclerView, but the view doesn't have any values. kotlin

class SummonerInfoActivity: AppCompatActivity() {
private lateinit var participantAdapter: ParticipantAdapter
private val recycler: RecyclerView by lazy {
findViewById(R.id.RecyclerView)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val Summoner = intent.getParcelableExtra<SummonerDTO>("SummonerDTO")
Log.e("Info","${Summoner}")
val retrofit2 = Retrofit.Builder()
.baseUrl("https://asia.api.riotgames.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
lolAPIForMatch = retrofit2.create(lolAPIService::class.java)
setContentView(R.layout.activity_summoner_info)
participantAdapter = ParticipantAdapter()
recycler.adapter = participantAdapter
recycler.layoutManager = LinearLayoutManager(this#SummonerInfoActivity)
getMatchIdBypuuid(Summoner?.puuId.orEmpty(),Summoner?.summonerName.orEmpty())
}
private fun getMatchIdBypuuid(puuid: String,summonerName: String){
lolAPIForMatch.getMatchIdBypuuid(puuid, 0,20, API_KEY)
.enqueue(object : Callback<List<String>> {
override fun onResponse(
call: Call<List<String>>,
response: Response<List<String>>
) {
if(response.isSuccessful.not()){
return
}
response.body()?.let {
it.forEach {
searchMatchInfoByMatchID(it,summonerName)
}
}
}
override fun onFailure(call: Call<List<String>>, t: Throwable) {
}
})
}
private fun searchMatchInfoByMatchID(matchId: String,summonerName: String){
lolAPIForMatch.getMatchInfoByMatchID(matchId, API_KEY)
.enqueue(object : Callback<MatchDTO>{
override fun onResponse(call: Call<MatchDTO>, response: Response<MatchDTO>) {
if(response.isSuccessful.not()){
return
}
response.body()?.let {
it.info.participants.filter {
it.summonerName == "${summonerName}"
}.forEach {
participantAdapter.participants.add(it)
}
}
}
override fun onFailure(call: Call<MatchDTO>, t: Throwable) {
}
})
}
}
class ParticipantAdapter: RecyclerView.Adapter<ParticipantAdapter.ViewHolder>() {
var participants = mutableListOf<ParticipantDTO>()
inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
fun bind(participant: ParticipantDTO){
itemView.findViewById<TextView>(R.id.kill).text = participant.kills.toString()
itemView.findViewById<TextView>(R.id.death).text = participant.deaths.toString()
itemView.findViewById<TextView>(R.id.assist).text = participant.assists.toString()
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ParticipantAdapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.item_match, parent, false))
}
override fun onBindViewHolder(holder: ParticipantAdapter.ViewHolder, position: Int) {
holder.bind(participants[position])
}
override fun getItemCount(): Int {
return participants.size
}
}
participantAdapter.participants.add(it)
The command is searchMatchInfoByMatchID
In the function, you can check that the value is entered correctly, but
If you check in the onCreate function, the value is not assigned.
I want to use the recycler view by properly assigning a value
I tried to solve this problem, but my skills were not enough.
I desperately need the advice of seniors.
I would really appreciate it if you could show me a code sample if possible