gpt4 book ai didi

安卓数据绑定(bind) : can I pass constructor parameter to my data variable?

转载 作者:行者123 更新时间:2023-11-29 15:40:22 25 4
gpt4 key购买 nike

我有一个 MovieViewModel 类,它在我的布局文件中用作变量。

<data>
<variable
name="vm"
type="udacity.nanodegree.android.p2.model.comum.MovieViewModel"/>;

</data>

根据Android Data Binding docs :

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 传递给我的类,最好通过布局文件中的构造函数:

public class MovieViewModel {
private Context context;

public MovieViewModel(Context context) {
this.context = context;
}
}

有办法吗?


如果不可能,我想将它传递给我的属性,例如:

<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 中使用上下文,如下所示:

public String getReleaseDateFormated (Context context){
return releaseDate == null? null: context.getString(R.string.dateToYear, releaseDate);

根据这个answer我可以这样做,但我尝试并收到错误:

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.MovieViewModel
file:C:\Users\alexandre\Udacity\Nanodegrees\AndroidDevelopment\P2-PopularMovies\app\src\main\res\layout\fragment_detail.xml
loc:74:40 - 74:70
****\ data binding error ****

最佳答案

"Is there a way to do that?

数据绑定(bind)框架没有创建 MovieViewModel 的实例。因此,当创建 MovieViewModel 的实例时,构造函数参数就是您的工作。

I tried and received the error

您的错误不是来自问题中的代码。错误指的是 releaseDateFormated()

关于安卓数据绑定(bind) : can I pass constructor parameter to my data variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418764/

25 4 0