如何通过数据绑定调用静态方法?

Khe*_*raj 6 android android-xml android-databinding

我想在layout.xml文件中调用我的Util类方法

<TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@{PreferenceUtil.getSavedUser().fullName}"/>
Run Code Online (Sandbox Code Playgroud)

我已经进口了 PreferenceUtil

<import type="com.amelio.utils.PreferenceUtil"/>
Run Code Online (Sandbox Code Playgroud)

PreferenceUtil.class有一些方法。

public class PreferenceUtil {

    public static LoginResponse getSavedUser() {
        SharedPreferences sf = Amelio.getInstance().getSharedPreferences(PREF, Context.MODE_PRIVATE);
        String userJson = sf.getString(PREF_USER_DATA, null);
        if (userJson == null || userJson.equals("")) {
            return null;
        }
        return new Gson().fromJson(userJson, LoginResponse.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题

    Found data binding errors.
****/ data binding error ****msg:cannot find method getSavedUser() in class com.amelio.utils.PreferenceUtil
file:D:\Khemraj\_AndroidStudioWorkspace_\amelioFinal\app\src\main\res\layout\activity_cart.xml
loc:94:40 - 94:68
****\ data binding error ****
Run Code Online (Sandbox Code Playgroud)

这是否有可能,还建议是否建议这样做。

小智 7

我希望您一定已经找到了答案,如果您仍在苦苦挣扎,请在下面找到答案。

    <data>
      <import type="com.amelio.utils.PreferenceUtil"/>
 </data>


<TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text='@{PreferenceUtil.getSavedUser()}' />
Run Code Online (Sandbox Code Playgroud)

请确保您的 LoginResponse 被标记为公开才能访问这些值。