Android导航体系结构组件-从ViewModel获取当前可见的片段

时间:2020-01-19 23:37:02

标签: android android-databinding android-architecture-components

我已经阅读了解决方法here,但就我而言,我想获取navHostFragment,然后导航至操作中的下一个目标。我想将onClick方法移至ViewController。

一些可用的代码:


class SimpleViewModel : ViewModel() {
    //        private set // This is to prevent external modification of the variable.
    private val _flowStepNumberArg =  MutableLiveData(1)
    val flowStepNumberArg: LiveData<Int> = _flowStepNumberArg

    fun onFragOneButtonPressed() {
        _flowStepNumberArg.value = 2
    }

    fun onClickFriend() {
        Log.d("BindingAdapters", "BUTTON CLICKED")
    }
}

class HomeFragment : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

      view.findViewById<Button>(R.id.navigate_action_button)?.setOnClickListener {
            val flowStepNumberArg = 1
            val action = HomeFragmentDirections.nextAction(flowStepNumberArg)
            findNavController().navigate(action)
        }
}

//in fragment_layout.xml::
    <data>
        <variable
            name="viewmodel"
            type="com.example.android.codelabs.navigation.data.SimpleViewModel" />
    </data>
    <Button
            android:id="@+id/next_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/next_step_button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/text"
            android:onClick="@{() -> viewmodel.onClickFriend2()}"
            />

0 个答案:

没有答案
相关问题