Как отразить изменения в recycleview родительской активности? - PullRequest
0 голосов
/ 17 июня 2020

Я также создал recycleView в моем основном действии, textView, который используется для отображения текста, если список, переданный в recycleView, пуст. Я дал кнопку удаления на карточке recycleView. Когда я открываю приложение, и если список пуст, то отображается textView для пустого представления, а recycleView невидим. Но когда я добавляю некоторые элементы и удаляю все элементы, этот textView для пустого текста не отображается. Как я могу решить эту проблему?

Activity_main. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="57dp"
        android:layout_height="64dp"
        android:layout_marginEnd="40dp"
        android:layout_marginBottom="40dp"
        android:clickable="true"
        android:onClick="addNewCredentials"
        app:backgroundTint="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@drawable/add"
        app:fabSize="normal"
        android:scaleType="center" />

    <TextView
        android:id="@+id/emptyView"
        android:layout_width="326dp"
        android:layout_height="71dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/empty_data"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/recyclerView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="1dp"
        android:layout_marginEnd="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

    </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.example.passwordmanager
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL,false)

        val db = DataBaseHandler(this)
        val detailsData = ArrayList(db.readCredentials())
        val adapter = CredentialAdapter(this,detailsData)
        recyclerView.adapter = adapter
        if(detailsData.isEmpty()){
            recyclerView.visibility = View.INVISIBLE
            findViewById<TextView>(R.id.emptyView).visibility = View.VISIBLE
        }
        else{
            recyclerView.visibility = View.VISIBLE
            findViewById<TextView>(R.id.emptyView).visibility = View.INVISIBLE
        }
    }


    fun addNewCredentials(view : View){
        print("hello world")
        val intent = Intent(this, AddDetailActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
    }
}

CredentialAdapter.kt

package com.example.passwordmanager

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.renderscript.RenderScript
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.RecyclerView
import android.content.Context.CLIPBOARD_SERVICE as CLIPBOARD_SERVICE1

//private var items: MutableList<CredentialsModel>,

class CredentialAdapter(ctx: Context, val credentialList : ArrayList<CredentialsModel>): RecyclerView.Adapter<CredentialAdapter.ViewHolder>() {
    var context = ctx

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val urlView = itemView.findViewById(R.id.urlView) as TextView
        val userNameView = itemView.findViewById(R.id.userNameView) as TextView
        val passwordView = itemView.findViewById(R.id.passwordView) as TextView
        val noteView = itemView.findViewById(R.id.noteView) as TextView
        val delButton = itemView.findViewById(R.id.delButton) as Button
        val cpyButton = itemView.findViewById(R.id.cpyButton) as Button
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.list_item_layout, parent, false)
        )
    }

    override fun getItemCount(): Int {
        return credentialList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val credential: CredentialsModel = credentialList[position]
        holder.urlView.text = credential.url
        holder.userNameView.text = credential.userName
        holder.passwordView.text = credential.password
        holder.noteView.text = credential.note

        holder.delButton.setOnClickListener {
            val db = DataBaseHandler(context)
            if (db.deleteData(credential.id)) {
                credentialList.removeAt(holder.getAdapterPosition())
                notifyItemRemoved(position)
            }
        }

        holder.cpyButton.setOnClickListener {
            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipUser = ClipData.newPlainText("username", credential.userName)
            clipboard.setPrimaryClip(clipUser)
            Toast.makeText(context, "Copied username to clipboard", Toast.LENGTH_SHORT).show()
            val clipPass = ClipData.newPlainText("password", credential.password)
            clipboard.setPrimaryClip(clipPass)
            Toast.makeText(context, "Copied password to clipboard", Toast.LENGTH_SHORT).show()
        }
    }
}

1 Ответ

1 голос
/ 17 июня 2020

Легко проверяйте размер вашего списка с помощью функции удаления и делайте emptyText видимым, когда размер списка равен нулю. Извините за код Java. Запишите эту функцию в основном действии

public void switchVisiblity(){
emptyTextView.setVisibility(View.VISIBLE);

}

Затем вызовите этот метод в функции удаления адаптера

holder.delButton.setOnClickListener {
        //write this below your code
        if(credentialList.size()==0){
           ((MainActivity)ctx).switchVisiblity();
       }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...