在使用ViewBinding时,我遇到了一些未记录的案例。
第一:如何获取包含的通用视图布局零件的绑定,主绑定仅查看主布局中的项目?
第二:如何获取包含的合并类型布局零件的绑定,再次主绑定仅查看主布局中的项目?
在使用ViewBinding时,我遇到了一些未记录的案例。
第一:如何获取包含的通用视图布局零件的绑定,主绑定仅查看主布局中的项目?
第二:如何获取包含的合并类型布局零件的绑定,再次主绑定仅查看主布局中的项目?
Answers:
的情况下:
<include
android:id="@+id/your_id"
layout="@layout/some_layout" />
这样在您的活动代码中:
private lateinit var exampleBinding: ActivityExampleBinding //activity_example.xml layout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
exampleBinding = ActivityExampleBinding.inflate(layoutInflater)
setContentView(exampleBinding.root)
//we will be able to access included layouts view like this
val includedView: View = exampleBinding.yourId.idOfIncludedView
//[...]
}
<?xml version="1.0" encoding="utf-8"?>
<merge 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"
tools:showIn="@layout/activity_example">
<TextView
android:id="@+id/some_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
</merge>
要正确绑定这种合并布局,我们需要:
在您的活动代码中:
private lateinit var exampleBinding: ActivityExampleBinding //activity_example.xml layout
private lateinit var mergeBinding: MergeLayoutBinding //merge_layout.xml layout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
exampleBinding = ActivityExampleBinding.inflate(layoutInflater)
//we need to bind the root layout with our binder for external layout
mergeBinding = MergeLayoutBinding.bind(exampleBinding.root)
setContentView(exampleBinding.root)
//we will be able to access included in merge layout views like this
val mergedView: View = mergeBinding.someView
//[...]
}
您的第一个问题,就是使用ViewBinding处理包含的布局,可以很容易地解决。
这是一个样本main_fragment.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view_main"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
</LinearLayout>
而且MainFragment.java可以像这样
public class MeaningFragment extends Fragment {
private MainFragmentBinding binding;
private ToolbarBinding toolbarBinding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = MainFragmentBinding.inflate(inflater, container, false);
toolbarBinding = binding.toolbar;
return binding.getRoot();
}
@Override
public void onDestroy() {
super.onDestroy();
toolbarBinding = null;
binding = null;
}
}
现在,您有两个绑定。其中之一是默认设置,下一个是来自随附的布局。
onCreate()
。谢谢。(使用a时遇到了一些麻烦DrawerLayout
)