app:visibleGone无法解析android Databinding

时间:2017-12-11 04:35:29

标签: android mvvm android-databinding

当我构建项目时。我在app上遇到错误:visibleGone

我还在build.gradle中启用了dataBinding并使用了android架构组件和mvvm。 项目targetSdkVersion26support lib version is 26.0.1

以下是错误消息

enter image description here

error: package com.****.****.databinding does not exist
error: cannot find symbol class ActivityMainBinding
Cannot find the setter for attribute 'app:visibleGone' with parameter type boolean on android.widget.Button.

这是我的 activity_main.xml

<layout xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="loading"
            type="boolean" />

    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.aungmyolwin.importdb.MainActivity">

        <Button
            android:id="@+id/btn_load_sql"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Load from SQL"
            app:visibleGone="@{!loading}"/>

        <Button
            android:id="@+id/btn_load_room"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Load from Room mapper"
            app:visibleGone="@{!loading}"/>

        <TextView
            android:id="@+id/tv_import_loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Importing database...."
            app:visibleGone="@{loading}"/>


    </LinearLayout>
</layout>

ActivityMain.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        binding.btnLoadRoom.setOnClickListener(this);
        binding.btnLoadSql.setOnClickListener(this);

        viewModels= ViewModelProviders.of(this).get(MainActivityViewModels.class);

    }
}

1 个答案:

答案 0 :(得分:15)

您需要为BindingAdapter创建自定义app:visibleGone(因为它不是可用方法)。
喜欢

public class BindingAdapters {
    @BindingAdapter("visibleGone")
    public static void showHide(View view, boolean show) {
        view.setVisibility(show ? View.VISIBLE : View.GONE);
    }
}

此外,如果你不想定义这样的方法,你可以这样做

<layout xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="loading"
            type="boolean" />
        <import type="android.view.View"/> <!-- remember to import -->
    </data>

    <LinearLayout >
        <Button
            android:visibility="@{loading ? View.GONE : View.VISIBLE}"
    </LinearLayout>
</layout>