android - 包含自定义视图时未传递 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);
}
两种方法(引用和文字值)都给出相同的结果。任何线索我可能做错了什么?
解决方案
推荐阅读
- tableau-desktop - 为什么在向仪表板添加筛选器时收到 Tableau 错误 6EA18A9E
- python - 如何将 db 获取的数据与 django 中用户选择的输入进行比较
- c# - asp net core发生错误时如何记录请求url?
- css - Tailwind 每次编译时都会生成错误的类
- android - 尝试在 Android 上运行我的 React Native 应用程序时出错
- autocomplete - 自动完成材料-ui 默认/首选项搜索
- java - 尝试使用 OracleDataSource 在 19c DB 中获取连接时出错
- vue.js - Vue 路由器(历史模式)和 Webpack 外部重定向处理
- sockets - 使用静态端口配置从 tcp 中的一个客户端套接字连接两个服务器套接字
- javascript - 是否可以在 TypeScript 中创建严格的“A 或 B”类型?