在自定义视图上使用DataBinding

时间:2017-03-27 05:52:02

标签: android android-databinding

我正在尝试创建自定义视图:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <FrameLayout
        android:id="@+id/container_fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateTint="#FFFFFF" />

    </FrameLayout>

</layout>

和Java:

public class ImageSlideshowView extends FrameLayout {
    private ViewImageSlideshowBinding binding;

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context);
    }

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        init(context);
    }

    private void init(@NonNull Context context) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        binding = ViewImageSlideshowBinding.inflate(layoutInflater, this, true);
    }
}

它有效,但不正确。

如果我在没有数据绑定的情况下使用merge标记而不是FrameLayout,我将获得以下布局(我最终希望获得布局):

  

- FrameLayout

     

--- ProgressBar

但是我不能将merge用于数据绑定,所以使用上面的XML我得到以下布局:

  

- FrameLayout

     

--- FrameLayout

     

---- ProgressBar

如您所见,还创建了一个FrameLayout。如何避免呢?

1 个答案:

答案 0 :(得分:0)

您的自定义视图是:visited。该布局包含FrameLayoutFrameLayout

尝试使用这样的布局:

ProgressBar

然后,当您将自定义视图包含在另一个视图中时,您可以按其类型引用它。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <com.yourcompany.yourapp.ImageSlideshowView
        android:id="@+id/container_fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateTint="#FFFFFF" />

    </com.yourcompany.yourapp.ImageSlideshowView>

</layout>