0

I will try to explain my issue step by step.

  1. I created data variable within xml file
     <data>

        <variable
            name="SLC90RViewModel"
            type="com.example.poy.ui.questionnaires.tools.SCL90RViewModel"/>
    </data>
  1. In my ViewModel i need to retrieve string array from resources (which is stored in xml file), so i passed app context into ViewModel constructor. Now it looks like this:
class SCL90RViewModel(val context: Context) : ViewModel() {
val item = context.getResources().getStringArray(R.array.firstArray)
}
  1. Finally, in my Fragment i want to assign LifecycleOwner and ViewModel to the binding:
class QuestionnaireFragment : Fragment(R.layout.fragment_questionnaire) {

    private var binding: FragmentQuestionnaireBinding? = null

    private val scl90rViewModel: SCL90RViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val fragmentBinding = FragmentQuestionnaireBinding.inflate(inflater, container, false)
        binding = fragmentBinding
        return fragmentBinding.root
    }

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

        binding?.apply {
            lifecycleOwner = viewLifecycleOwner
            SCL90RViewModel = scl90rViewModel
        }
    }
}

However, SCL90RViewModel in binding?.apply{} is outlined with red and message "Classifier 'SCL90RViewModel' does not have a companion object, and thus must be initialized here" pops up. How can i fix it?

LAO
  • 87
  • 10

1 Answers1

0

SCL90RViewModel is ambiguous here, it can be the binding variable or the ViewModel class. So use this inside the apply block to refer to the binding variable.

binding?.apply {
            lifecycleOwner = viewLifecycleOwner
            this.SCL90RViewModel = scl90rViewModel
        }
Alpha 1
  • 4,118
  • 2
  • 17
  • 23
  • i tried this solution, but now SCL90RViewModel is an unresolved reference. Tho variable name in the xml and in the fragment is the same – LAO Apr 16 '21 at 11:34
  • Have you tried renaming `SCL90RViewModel` in the xml to something else? – Alpha 1 Apr 16 '21 at 11:43
  • oh, it actually helped... Thank you! Tho im pazzled, is it because variable and ModelView has the same name but in different register, or is it because variable name contains numbers in it? – LAO Apr 16 '21 at 11:46
  • There no official documentation for this, But I think there some restrictions related to the variable names in the XML. – Alpha 1 Apr 16 '21 at 11:52