将生成一个名为context的特殊变量,用于绑定 根据需要的表达式.上下文的值是来自 根视图的getContext().上下文变量将被覆盖 具有该名称的显式变量声明. A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name.我需要将此特殊变量context最好由布局文件中的构造函数传递给我的类:I need to pass this special variable context to my class preferably by the constructor from layout file:public class MovieViewModel { private Context context; public MovieViewModel(Context context) { this.context = context; }}有没有办法做到这一点?Is there a way to do that?如果不可能的话,我想将其传递给我的属性,例如:If not possible, I would like to pass it to my attributes, like:<TextView android:id="@+id/text_release" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:padding="2dp" android:text="@{vm.releaseDateFormated(context) ?? ``}" tools:text="0000"/>要在MovieViewModel中使用上下文,如下所示:To use context in MovieViewModel as below:public String getReleaseDateFormated (Context context){ return releaseDate == null? null: context.getString(R.string.dateToYear, releaseDate);根据此答案,我可以这样做,但是我尝试并收到错误:According with this answer I could do that, but I tried and received the error:Error:Execution failed for task ':app:compileDebugJavaWithJavac'.> java.lang.RuntimeException: Found data binding errors.****/ data binding error ****msg:cannot find method releaseDateFormated(android.content.Context) in class udacity.nanodegree.android.p2.model.comum.MovieViewModelfile:C:\Users\alexandre\Udacity\Nanodegrees\AndroidDevelopment\P2-PopularMovies\app\src\main\res\layout\fragment_detail.xmlloc:74:40 - 74:70****\ data binding error ****推荐答案 有办法吗? "Is there a way to do that?数据绑定框架未创建MovieViewModel的实例.因此,当 you 创建MovieViewModel的实例时,构造函数参数就是您的工作.The data binding framework is not creating an instance of MovieViewModel. Hence, constructor parameters are your job, when you create the instance of MovieViewModel. 我尝试并收到错误 I tried and received the error您的错误并非来自问题代码.错误是指releaseDateFormated().Your error is not coming from the code in your question. The error refers to releaseDateFormated(). 这篇关于Android DataBinding:我可以将构造函数参数传递给我的数据变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 18:18