Фрагмент лезет на другой фрагмент во время навигации - PullRequest
0 голосов
/ 19 сентября 2019

У меня есть некоторые проблемы с анимацией, я думаю, дело в том, что, когда я перемещаюсь от одного фрагмента к другому (от DayFragment до LessonFragment), анимация работает неправильно, и у меня есть 2 секунды этого просмотра (один фрагмент взбирается на другой):

У меня недостаточно репутации для публикации изображений, извините за это. Ссылки для просмотра проблемы с анимацией: https://i.imgur.com/XYZi9cR.png, https://i.imgur.com/ArXtDBg.png

Основная навигация: У меня недостаточно репутации для публикации изображений, извините за это. Ссылки: https://i.imgur.com/chy5slb.png,

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/main_navigation"
            app:startDestination="@id/scheduleFragment">
    <fragment
            android:id="@+id/scheduleFragment"
            android:name="andy.product.schedulekpi.ui.fragments.schedule.ScheduleFragment"
            android:label="schedule_fragment"
            tools:layout="@layout/schedule_fragment">

        <action
            android:id="@+id/action_scheduleFragment_to_dayFragment"
            app:destination="@id/dayFragment"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim" />


    </fragment>

    <fragment
            android:id="@+id/archiveFragment"
            android:name="andy.shedulekpi.ui.fragments.archive.ArchiveFragment"
            android:label="archive_fragment"
            tools:layout="@layout/archive_fragment">
        <action
            android:id="@+id/action_archiveFragment_to_scheduleFragment"
            app:destination="@id/scheduleFragment"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"
            app:popUpTo="@+id/scheduleFragment"
            app:popUpToInclusive="true" />
    </fragment>
    <fragment
            android:id="@+id/teachersFragment"
            android:name="andy.product.schedulekpi.ui.fragments.teachers.TeachersFragment"
            android:label="teachers_fragment"
            tools:layout="@layout/teachers_fragment"/>
    <fragment
            android:id="@+id/settingsFragment"
            android:name="andy.product.schedulekpi.ui.fragments.settings.SettingsFragment"
            android:label="settings_fragment"
            tools:layout="@layout/settings_fragment"/>
    <fragment

            android:id="@+id/dayFragment"
            android:name="andy.product.schedulekpi.ui.fragments.day.DayFragment"
            android:label="day_fragment"
            tools:layout="@layout/day_fragment">

        <argument
                android:name="selectedWeek"
                app:argType="integer"
                android:defaultValue="-1"/>

        <argument
                android:name="groupId"
                app:argType="string"
                android:defaultValue="null"/>

        <argument
                android:name="day"
                app:argType="string"
                android:defaultValue="null"/>


        <argument
                android:name="lessonId"
                app:argType="string"/>

        <argument
                android:name="color"
                app:argType="integer"/>

        <argument
                android:name="lessonWeek"
                app:argType="integer"/>

        <argument
                android:name="lessonDay"
                app:argType="string"/>

        <argument
                android:name="lessonStart"
                app:argType="string"/>

        <argument
                android:name="lessonEnd"
                app:argType="string"/>

        <argument
                android:name="lessonName"
                app:argType="string"/>

        <argument
                android:name="lessonRoom"
                app:argType="string"/>

        <argument
                android:name="days"
                app:argType="integer"
                android:defaultValue="0"/>
        <action
            android:id="@+id/action_dayFragment_to_lessonFragment"
            app:destination="@+id/lessonFragment"
            app:exitAnim="@anim/nav_default_enter_anim"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"
            app:popUpToInclusive="true" />

    </fragment>
    <fragment
            android:id="@+id/lessonFragment"
            android:name="andy.product.schedulekpi.ui.fragments.lesson.LessonFragment"
            android:label="lesson_fragment"
            tools:layout="@layout/lesson_fragment" >

        <argument
                android:name="lessonWeek"
                android:defaultValue="1"
                app:argType="integer"/>

        <argument
                android:name="lessonDay"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
                android:name="lessonStart"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
                android:name="lessonEnd"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
                android:name="lessonName"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
                android:name="lessonRoom"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
            android:name="lessonType"
            app:argType="string"
            android:defaultValue="null"/>

        <argument
                android:name="lessonTeacherName"
                app:argType="string"
                android:defaultValue="null"/>

        <argument
                android:name="lessonId"
                app:argType="string"
                android:defaultValue="null"/>

        <action
                android:id="@+id/action_lessonFragment_to_notesFragment"
                app:destination="@id/notesFragment" />
        <action
            android:id="@+id/action_lessonFragment_to_dayFragment"
            app:destination="@id/dayFragment"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim" />

    </fragment>

    <fragment
            android:id="@+id/notesFragment"
            android:name="andy.product.schedulekpi.ui.fragments.notes.NotesFragment"
            android:label="notes_fragment"
            tools:layout="@layout/notes_fragment" >

        <argument
                android:name="lessonName"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
                android:name="lessonId"
                android:defaultValue="null"
                app:argType="string"/>

        <argument
                android:name="lessonDay"
                android:defaultValue="null"
                app:argType="string"/>

    </fragment>


</navigation>

DayFragment.kt:

package andy.product.schedulekpi.ui.fragments.day

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import andy.product.schedulekpi.R
import andy.product.schedulekpi.logic.events.GoToNextFragmentEvent
import andy.product.schedulekpi.logic.events.ShowSnackbarEvent
import andy.product.schedulekpi.repository.database.models.Lesson
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.day_fragment.*

class DayFragment : Fragment() {

    companion object {
        fun newInstance() = DayFragment()
    }

    private lateinit var viewModel: DayViewModel

    private val safeArgs: DayFragmentArgs by navArgs()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.day_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(DayViewModel::class.java)

        checkHighlightedAndHighlightIfNeed()

        dayName.text = safeArgs.day

        stopDownload()
        setupRecyclerView()

        viewModel.fetchLessons(safeArgs.groupId, safeArgs.selectedWeek, safeArgs.day)

        observeFetched()
        observeLessons()
        observeTimer()
        observeEvents()
    }

    private fun stopObserve() {
        viewModel.eventData.removeObservers(this)
        viewModel.lessonsData.removeObservers(this)
        viewModel.timeToEnd.removeObservers(this)
        viewModel.fetched.removeObservers(this)
    }

    private fun observeEvents() {
        viewModel.eventData.observe(this, Observer {
            when (it) {
                is ShowSnackbarEvent -> Snackbar.make(mainEelementDay, it.res, it.duration)
                    .show()
                is GoToNextFragmentEvent<*> -> {
                    if (it.info is Lesson) {
                        try {
                            goToDetailLessonFragment(it.info)
                        } catch (e: IllegalArgumentException) {
                            // User tried tapping 2 links at once!
                            Log.d("ScheduleKpi","Can't open 2 links at once!")
                        }
                    }
                }
            }
        })
    }

    private fun goToDetailLessonFragment(lesson: Lesson) {
        val action = DayFragmentDirections.actionDayFragmentToLessonFragment()
            .setLessonDay(lesson.dayName)
            .setLessonEnd(lesson.timeEnd)
            .setLessonName(lesson.lessonFullName)
            .setLessonRoom(lesson.lessonRoom)
            .setLessonStart(lesson.timeStart)
            .setLessonTeacherName(lesson.teacherName)
            .setLessonType(lesson.lessonType)
            .setLessonWeek(lesson.lessonWeek.toInt())
            .setLessonId(lesson.lessonId)

        findNavController().navigate(action)
    }

    private fun observeTimer() {
        viewModel.timeToEnd.observe(this, Observer {
            textViewTimeToEnd.text = it
        })
    }

    private fun checkHighlightedAndHighlightIfNeed() {
        viewModel.highlightLesson(safeArgs.day, safeArgs.lessonDay,
            safeArgs.selectedWeek, safeArgs.lessonWeek, safeArgs.lessonId, safeArgs.color,
            safeArgs.lessonStart, safeArgs.lessonEnd, safeArgs.days)

        if (safeArgs.lessonWeek != safeArgs.selectedWeek || safeArgs.day != safeArgs.lessonDay) {
            textViewTimeToEnd.visibility = View.GONE
            clockImage.visibility = View.GONE
        } else {
            // startService()
        }

        textViewTimeToEnd.setTextColor(safeArgs.color)

    }


//    private fun startService() {
//        val serviceIntent = Intent(this.context, TimerNotificationService::class.java)
//        serviceIntent.putExtra("lessonName", safeArgs.lessonName)
//        serviceIntent.putExtra("lessonRoom", safeArgs.lessonRoom)
//        serviceIntent.putExtra("day", safeArgs.day)
//        serviceIntent.putExtra("lessonDay", safeArgs.lessonDay)
//        serviceIntent.putExtra("lessonWeek", safeArgs.lessonWeek)
//        serviceIntent.putExtra("highlightedColor", safeArgs.color)
//        serviceIntent.putExtra("days", safeArgs.days)
//        serviceIntent.putExtra("lessonEnd", safeArgs.lessonEnd)
//        serviceIntent.putExtra("lessonStart", safeArgs.lessonStart)
//        serviceIntent.putExtra("lessonName", safeArgs.lessonName)
//
//        activity!!.startService(serviceIntent)
//    }

    private fun observeFetched() {
        viewModel.fetched.observe(this, Observer {
            if (it == false) {
                startDownload()
            }

            if (it == true) {
                stopDownload()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.stopTimer()
        stopObserve()
    }

    override fun onPause() {
        super.onPause()

        viewModel.stopTimer()
        stopObserve()

    }

    override fun onResume() {
        super.onResume()

        checkHighlightedAndHighlightIfNeed()
    }


    private fun setupRecyclerView() {
        recyclerViewLessons.layoutManager = LinearLayoutManager(this.context, RecyclerView.VERTICAL, false)
    }

    private fun observeLessons() {
        viewModel.lessonsData.observe(this, Observer {
            recyclerViewLessons.adapter = viewModel.createAdapter(it)
        })
    }

    private fun showToast(message: String, duration: Int) {
        Toast.makeText(this.context, message, duration).show()
    }

    private fun stopDownload() {
        progressBarDay.visibility = View.GONE
        backdrop_day.visibility = View.GONE
    }

    private fun startDownload() {
        progressBarDay.visibility = View.VISIBLE
        backdrop_day.visibility = View.VISIBLE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stopObserve()
    }

}

LessonFragmnet.kt

package andy.product.schedulekpi.ui.fragments.lesson

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import andy.product.schedulekpi.R
import kotlinx.android.synthetic.main.lesson_fragment.*

class LessonFragment : Fragment() {

    companion object {
        fun newInstance() = LessonFragment()
    }

    private lateinit var viewModel: LessonViewModel

    private val safeArgs: LessonFragmentArgs by navArgs()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.lesson_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(LessonViewModel::class.java)

        setInfo()

        btnShowNotes.setOnClickListener {
            goToNotesFragment()
        }
    }

    private fun setInfo() {
        lessonFillName.text = safeArgs.lessonName
        inflateInfo(teacherContainer, safeArgs.lessonTeacherName, teacherFullName)
        inflateInfo(timeContainer, safeArgs.lessonStart + " - " + safeArgs.lessonEnd, time)
        inflateInfo(roomContainer, safeArgs.lessonRoom, lessonRoom)
        inflateInfo(typeContainer, safeArgs.lessonType, lessonType)
        inflateInfo(dayContainer, safeArgs.lessonDay, lessonDay)
        inflateInfo(weekContainer, safeArgs.lessonWeek.toString(), lessonWeek)
    }

    private fun inflateInfo(container: LinearLayout, value: String, textView: TextView) {
        if (value.isEmpty() || value == "null") {
            container.visibility = View.GONE
        } else {
            textView.text = value
        }
    }

    private fun goToNotesFragment() {
        val action = LessonFragmentDirections.actionLessonFragmentToNotesFragment()
            .setLessonDay(safeArgs.lessonDay)
            .setLessonId(safeArgs.lessonId)
            .setLessonName(safeArgs.lessonName)

        findNavController().navigate(action)

    }
}

Я читал раньше, и кто-то сказал, что проблема с анимацией может быть вызвана наблюдателями во Fragment (потому что обновление от viewmodel приходит каждую секунду (у меня таймер в viewModel)), но я отменил регистрацию от наблюдателей в onPause, так что решение не работает для меня, или я сделал что-то не так.

Итак, цель исправить анимацию

Спасибо за помощь, я пытаюсь исправитьего проблемы за неделю.

...