问题
I have a MovieViewModel
class that is used as variable in my layout file.
<data>
<variable
name="vm"
type="udacity.nanodegree.android.p2.model.comum.MovieViewModel"/>;
</data>
According with 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.
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"/>
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.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 ****
回答1:
"Is there a way to do that?
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
Your error is not coming from the code in your question. The error refers to releaseDateFormated()
.
来源:https://stackoverflow.com/questions/41418764/android-databinding-can-i-pass-constructor-parameter-to-my-data-variable