我在我的 android 项目中使用数据绑定,并且我的 dashboard_fragment_layout.xml 包含 LinearLayout,其中包含 TextView 和 CustomView:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.ui.dashboard.DashboardFragment">
<data>
<variable
name="ViewModel"
type="com.example.ui.dashboard.DashboardViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvSome"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<view
android:id="@+id/viewCustom"
class="com.example.ui.dashboard.CustomView"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="bottom|center_horizontal" />
</LinearLayout>
</layout>
当我尝试通过生成的 FragmentDashboardBinding 访问我的自定义视图时:
mCustomView = mBinding.viewCustom;
我在 AndroidStudio 中收到“无法解析符号 viewCustom”。而且我对 TextView 没有这个问题,它可以从 mBinding 对象访问:
mSomeTextView = mBinding.tvSome; // all fine, no errors
我总是在自定义视图中遇到此错误,访问自定义视图对象的唯一方法是使用 findViewById 以旧方式执行此操作:
mCustomView = view.findViewById(R.id.viewCustom); // that works
全部一起:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewDataBinding = DataBindingUtil.inflate(inflater, fragment_dashboard_layout, container, false);
view = mViewDataBinding.getRoot();
mCustomView = mViewDataBinding.viewCustom; // 'Can't resolve symbol viewCustom
mTextView = mViewDataBinding.tvSome; // all fine
mCustomView = view.findViewById(R.id.viewCustom); // that works
}
如何通过生成的数据绑定对象访问自定义视图?