我正在使用片段观察片段中的实时数据。每当我转移到另一个片段时,让我们说片段B,然后再说A,就将相同的视图模型分配给具有现有LivaData的片段A,就像上一个一样,它开始响应先前的实时数据
这是我的片段
class Notifications : BaseFragment<FragmentNotificationsBinding>(),RecyclerListner {
private var batcheDailog: AlertDialog? = null
private var dailogview: View? = null
private var document_id: String? = null
private var document_url: String? = null
private lateinit var notificationViewModel: NotificationViewModel
private lateinit var adapter: NotificationHistory
private var SEM1_SELECTED:Boolean = false
private var SEM2_SELECTED:Boolean = false
private var SEM3_SELECTED:Boolean = false
private var SEM4_SELECTED:Boolean = false
private var SEM5_SELECTED:Boolean = false
private var SEM6_SELECTED:Boolean = false
override val layoutId: Int
get() = R.layout.fragment_notifications
override fun init() {
notificationViewModel = ViewModelProvider(this).get(NotificationViewModel::class.java)
Log.d("viewmodel",notificationViewModel.toString())
val option = FirestoreRecyclerOptions.Builder<NotificationDto>()
.setQuery(Reference.Notification_Ref, NotificationDto::class.java)
.setLifecycleOwner(this)
.build()
adapter = NotificationHistory(this,option)
binding.rvHistory.layoutManager = LinearLayoutManager(context)
binding.rvHistory.adapter = adapter
val callback: ItemTouchHelper.SimpleCallback = object :
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
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
) {
RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addBackgroundColor(ContextCompat.getColor(context!!, R.color.red))
.addActionIcon(R.drawable.ic_delete)
.addSwipeRightLabel("Delete")
.setSwipeRightLabelTextSize(Dimension.DP,45f)
.setSwipeRightLabelColor(ContextCompat.getColor(context!!,R.color.white))
.create()
.decorate()
super.onChildDraw(c,recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
document_id = adapter.snapshots.getSnapshot(viewHolder.adapterPosition).reference.id
document_url = adapter.snapshots.getSnapshot(viewHolder.adapterPosition).getString("document_url")
if(Validator.validateNull(document_url)) notificationViewModel.deleteNotification(document_id!!)
else notificationViewModel.deleteAttachment(document_url!!)
}
}
val itemTouchHelper = ItemTouchHelper(callback)
itemTouchHelper.attachToRecyclerView(binding.rvHistory)
val yoyo = mutableListOf<String>()
yoyo.add("SEM-1")
yoyo.add("SEM-2")
yoyo.add("SEM-3")
yoyo.add("SEM-4")
initdailog(yoyo)
setlistner()
setobserver()
// notificationViewModel.getBatchLList()
}
private fun initdailog(batches: List<*>) {
dailogview = layoutInflater.inflate(R.layout.dailog_select_sem,null,false)
if(!batches.contains("SEM-1")) dailogview!!.toogle_batches.btn_sem1.visibility = View.GONE
if(!batches.contains("SEM-2")) dailogview!!.toogle_batches.btn_sem2.visibility = View.GONE
if(!batches.contains("SEM-3")) dailogview!!.toogle_batches.btn_sem3.visibility = View.GONE
if(!batches.contains("SEM-4")) dailogview!!.toogle_batches.btn_sem4.visibility = View.GONE
if(!batches.contains("SEM-5")) dailogview!!.toogle_batches.btn_sem5.visibility = View.GONE
if(!batches.contains("SEM-6")) dailogview!!.toogle_batches.btn_sem6.visibility = View.GONE
batcheDailog = MaterialAlertDialogBuilder(context).create()
dailogview!!.toogle_batches.addOnButtonCheckedListener { group, checkedId, isChecked ->
if(isChecked){
when(checkedId){
R.id.btn_sem1-> SEM1_SELECTED = true
R.id.btn_sem2-> SEM2_SELECTED = true
R.id.btn_sem3-> SEM3_SELECTED = true
R.id.btn_sem4-> SEM4_SELECTED = true
R.id.btn_sem5-> SEM5_SELECTED = true
R.id.btn_sem6-> SEM6_SELECTED = true
}
}
else{
when(checkedId){
R.id.btn_sem1-> SEM1_SELECTED = false
R.id.btn_sem2-> SEM2_SELECTED = false
R.id.btn_sem3-> SEM3_SELECTED = false
R.id.btn_sem4-> SEM4_SELECTED = false
R.id.btn_sem5-> SEM5_SELECTED = false
R.id.btn_sem6-> SEM6_SELECTED = false
}
}
}
dailogview!!.btn_next.setOnClickListener {
if(!SEM1_SELECTED && !SEM2_SELECTED &&!SEM3_SELECTED && !SEM4_SELECTED && !SEM5_SELECTED && !SEM6_SELECTED ) showToast("Select At Least One",0)
else{
val selectedBatches = ArrayList<String>()
if(SEM1_SELECTED) selectedBatches.add("SEM-1")
if(SEM2_SELECTED) selectedBatches.add("SEM-2")
if(SEM3_SELECTED) selectedBatches.add("SEM-3")
if(SEM4_SELECTED) selectedBatches.add("SEM-4")
if(SEM5_SELECTED) selectedBatches.add("SEM-5")
if(SEM6_SELECTED) selectedBatches.add("SEM-6")
startActivity(SendNotification.getCallingIntent(context!!,selectedBatches))
}
}
batcheDailog!!.setView(dailogview)
}
private fun setobserver() {
notificationViewModel.getBatchLiveData.observe(viewLifecycleOwner, Observer {
when(it.status){
ResponseData.Status.LOADING -> showLoadingDailog("Please Wait",it.message!!)
ResponseData.Status.SUCCESS -> {val batches = it.data as List<*>
hideLoadingDailog()
initdailog(batches)
}
ResponseData.Status.ERROR -> showErrorDailog("Error",it.message!!)
}
})
notificationViewModel.getdeleteAttachmentLiveData.observe(viewLifecycleOwner, Observer {
when(it.status){
ResponseData.Status.LOADING -> showLoadingDailog("Please Wait",it.message!!)
ResponseData.Status.SUCCESS -> notificationViewModel.deleteNotification(document_id!!)
ResponseData.Status.ERROR -> showErrorDailog("Error",it.message!!)
}
})
notificationViewModel.getdeleteNotificationData.observe(viewLifecycleOwner, Observer {
when(it.status){
ResponseData.Status.LOADING -> showLoadingDailog("Please Wait",it.message!!)
ResponseData.Status.SUCCESS -> showSuccessDailog("Done","Deleted Successfully")
ResponseData.Status.ERROR -> showErrorDailog("Error",it.message!!)
}
})
}
private fun setlistner() {
binding.btnNotificationHistory.setOnClickListener {
binding.clMain.visibility = View.GONE
binding.clHistory.visibility = View.VISIBLE
}
binding.btnBack.setOnClickListener{
binding.clHistory.visibility = View.GONE
binding.clMain.visibility = View.VISIBLE
}
binding.btnSelectbatch.setOnClickListener {
batcheDailog!!.show()
}
batcheDailog!!.setOnCancelListener {
SEM1_SELECTED = false
SEM2_SELECTED = false
SEM3_SELECTED = false
SEM4_SELECTED = false
SEM5_SELECTED = false
SEM6_SELECTED = false
dailogview!!.toogle_batches.clearChecked()
}
binding.btnAllbatch.setOnClickListener {
startActivity(SendNotification.getCallingIntent(context!!,null))
}
}
override fun onClick(id: String, notificationDto: NotificationDto) {
startActivity(ActivityNotificationDetail.getCallingIntent(context!!,notificationDto,id))
}
}
这是我的viewModel
class NotificationViewModel:BaseViewModel() {
val getUploadDocumentLiveData:MutableLiveData<ResponseData<Any>> = MutableLiveData<ResponseData<Any>>()
val getSendNotificationLiveData:MutableLiveData<ResponseData<Any>> = MutableLiveData<ResponseData<Any>>()
val getBatchLiveData:MutableLiveData<ResponseData<Any>> = MutableLiveData<ResponseData<Any>>()
val getdeleteAttachmentLiveData:MutableLiveData<ResponseData<Any>> = MutableLiveData<ResponseData<Any>>()
val getdeleteNotificationData:MutableLiveData<ResponseData<Any>> = MutableLiveData<ResponseData<Any>>()
val getUpdateNotificationLiveData:MutableLiveData<ResponseData<Any>> = MutableLiveData<ResponseData<Any>>()
fun sendNotification(notificationDto: NotificationDto){
getSendNotificationLiveData.value = ResponseData.loading("Sending Notification")
compositeDisposable.add(repository!!.sendNotification(notificationDto).
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribe({
getSendNotificationLiveData.value = ResponseData.success()
},{
getSendNotificationLiveData.value = ResponseData.error(it.message!!)
})
)
}
fun uploadDocument(path:Uri,reference: StorageReference){
getUploadDocumentLiveData.value = ResponseData.loading("Uploading Document. This may take some time depending on the file size")
compositeDisposable.add(repository!!.getUrl(path, reference).
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribeWith(object : DisposableSingleObserver<String>(){
override fun onSuccess(t: String) {
getUploadDocumentLiveData.value = ResponseData.success("Done",t)
}
override fun onError(e: Throwable) {
getUploadDocumentLiveData.value = ResponseData.error(e.message!!)
}
}))
}
fun updateNotification(id:String,notificationDto: NotificationDto){
getUpdateNotificationLiveData.value = ResponseData.loading("This may take some time depending on the file size")
compositeDisposable.add(repository!!.updateNotification(id, notificationDto).
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribe({
getUpdateNotificationLiveData.value = ResponseData.success()
},{
getUpdateNotificationLiveData.value = ResponseData.error(it.message!!)
}))
}
fun deleteAttachment(url:String){
getdeleteAttachmentLiveData.value = ResponseData.loading("Connecting To the server")
compositeDisposable.add(repository!!.deleteFile(url).
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribe({
getdeleteAttachmentLiveData.value = ResponseData.success()
},{
getdeleteAttachmentLiveData.value = ResponseData.error(it.message!!)
}))
}
fun deleteNotification(id:String){
getdeleteNotificationData.value = ResponseData.loading("Deleting Notification")
compositeDisposable.add(repository!!.deleteNotification(id).
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribe({
getdeleteNotificationData.value = ResponseData.success()
},{
getdeleteNotificationData.value = ResponseData.error(it.message!!)
}))
}
}
这是我的片段曼格班
class DashboardAdapter(manager:FragmentManager):FragmentPagerAdapter(manager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int): Fragment {
when (position){
0-> return Notifications()
1-> return Batches()
2-> return Updates()
else -> return Notifications()
}
}
override fun getCount(): Int = 3
}
这是我的BaseFragment **
abstract class BaseFragment<T : ViewDataBinding> : Fragment() {
abstract val layoutId: Int
protected lateinit var binding: T
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, layoutId, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
init()
}
abstract fun init()
fun showToast(msg:String,duration:Int){
getBaseActivity().showToast(msg,duration)
}
fun hideLoadingDailog(){
getBaseActivity().hideLoadingDailog()
}
fun showLoadingDailog(title:String,msg:String){
getBaseActivity().showLoadingDailog(title,msg)
}
fun showLoadingDailog(title:String,msg:String,animid:Int){
getBaseActivity().showLoadingDailog(title,msg,animid)
}
fun showSuccessDailog(title:String,msg:String){
getBaseActivity().showSuccessDailog(title,msg)
}
fun showErrorDailog(title:String,msg:String){
getBaseActivity().showErrorDailog(title,msg)
}
fun showFinalDailog(title:String,msg:String,positivebutton :String,negativebutton:String,listner: AbstractDialog.OnClickListener){
getBaseActivity().showFinalDailog(title,msg,positivebutton,negativebutton,listner)
}
fun showFinalDailog(title:String,msg:String,positivebutton :String,listner: AbstractDialog.OnClickListener){
getBaseActivity().showFinalDailog(title,msg,positivebutton,listner)
}
protected fun getBaseActivity(): BaseActivity<*> {
return (activity as BaseActivity<*>)
}
}
答案 0 :(得分:0)
在您的BaseFragment
中,您正在从onActivityCreated
调用init(如果您不知道,则不推荐使用)。
相反,请覆盖方法onViewCreated
并从其中调用init
。