Как реализовать с помощью viewModels? - PullRequest
0 голосов
/ 04 марта 2020

Я пытался реализовать LiveData и View Model. В этом приложении число отображается на экране, и мы можем добавить пять или минус один. Ранее я использовал viewModelProvider, но теперь он устарел, и я использую "by viewmodels", но он показывает ошибку ann

fragOne.kt

class fragOne : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        var binding = DataBindingUtil.inflate<FragmentFragoneBinding>(
            inflater,
            R.layout.fragment_fragone,
            container,
            false
        )

        //viewModel = ViewModelProviders.of(this).get(fragViewModel::class.java)
        // Create the observer which updates the UI.
        val viewModel: fragViewModel by **viewModels()**
        val nameObserver = Observer<Int> {
            viewModel.num.value=it

        }
        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        viewModel.num.observe(viewLifecycleOwner,nameObserver)
        // setting on Click listener for add button
        binding.add.setOnClickListener()
        {

            //updateNumber()
            viewModel.num.setValue(viewModel.addFive())
        }

        // setting on on Click Listener for minus button
        binding.minus.setOnClickListener()
        {
            viewModel.num.setValue(viewModel.minusOne())
            //updateNumber()
        }


        return binding.root
    }

        // Always call the superclass so it can save the view hierarchy state
}

fragViewModel

import androidx.lifecycle.ViewModel

class fragViewModel:ViewModel()
{
    val num: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    // Initializing num=0
    init {
         num .value= 0
    }
    // Functions to add five or subtract one

    fun addFive():Int
    {
        var newNumber:Int?=num.value

        return newNumber?.plus(5)?:0
    }

     fun minusOne():Int
    {
        var newNumber:Int?=num.value

        return newNumber?.minus(1)?:0
    }
}

В fragOne есть ошибка, показывающая в viewModels . Так в чем же ошибка. пожалуйста, дайте мне знать, если кто-то захочет получить код, я буду загружать его в Github

build.gradle

    def lifecycle_version = "2.2.0"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation "androidx.core:core-ktx:1.2.0"
    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...