首页 > 解决方案 > 包含自定义视图时未传递 Android 数据绑定数据

问题描述

我想将我的自定义视图包含在片段中的数据绑定中,并将值传递给绑定。不幸的是,这些值没有被传递,getter 总是返回 null。

这是我的自定义视图 custom_view.xml

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

<data>

    <variable
        name="label"
        type="String" />

</data>

<com.my.package.CustomView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text='@{label}' />

</com.my.package.CustomView>

及其代码CustomView.java

public class CustomView extends ConstraintLayout {

    CustomViewBinding binding;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        binding = CustomViewBinding.bind(this);
        Log.i("binding", "l:" + binding.getLabel()); // I/binding: l:null
    }
}

现在这个视图包含在 fragment.xml 中

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.HomeFragment">

        <include
            layout="@layout/custom_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:label="@{@string/main_menu_some_title}" />

        <include
            layout="@layout/custom_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:label='@{"asd"}' />

</LinearLayout>

此外,MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle =
            new ActionBarDrawerToggle(this, drawer, toolbar, string.navigation_drawer_open,
                    string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    DataBindingUtil.setContentView(this, R.layout.activity_main);
}

两种方法(引用和文字值)都给出相同的结果。任何线索我可能做错了什么?

标签: androidandroid-layoutandroid-fragmentsandroid-xmlandroid-databinding

解决方案


推荐阅读