我想将我的自定义视图包括来自片段的数据绑定并传递要绑定的值。不幸的是,这些值没有传递,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);
}
两种方法(引用和文字值)给出相同的结果。有什么线索可能是我做错了吗?