android - 无法从活动访问另一个布局内的布局
问题描述
我有多个按层次顺序定义的布局,问题是当我尝试访问在内部布局中定义的项目时,它给了我NullPointerException
。
这是我的布局结构。
R.layout.activity_map
-> <include layout="content_map">
-> <include layout="terrace_parent_map">
-> <include layout="terrace_collection_map">
现在terrace_collection_map
有约束布局,我需要从活动中访问。以下是布局。
<android.support.constraint.ConstraintLayout
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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/constraintTerraceLayout"
>
</android.support.constraint.ConstraintLayout>
但是当我尝试获取 id 时constraintLayout
,它返回 null。
constraintTerraceLayout= findViewById(R.id.constraintTerraceLayout);
**编辑 - Terrace_collection_map **
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/constraintTerraceLayout"
>
<ImageView
android:id="@+id/imageView30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="@drawable/terrace" />
</android.support.constraint.ConstraintLayout>
解决方案
尝试添加<merge /
> 标记,以帮助您在将一个布局包含在另一个布局中时消除视图层次结构中的冗余视图组。
例如,如果您的主布局是垂直LinearLayout
的,其中两个连续的视图可以在多个布局中重复使用layout
,那么放置两个视图的可重复使用的视图需要它自己的根视图。
所以使用<merge>
标签,如果activity_map.xml
有LinearLayout
作为父标签。然后更改您的terrace_collection_map.xml
父标签,如下所示:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
//..........Your Custom Layout Design...........
</merge>
这个链接可以简单地帮助你,https://developer.android.com/training/improving-layouts/reusing-layouts
推荐阅读
- android - 使用 pojo 的 Retrofit + RxJava 错误中的空指针
- angular - 与 routerLink @Input() 共享组件
- php - mysql插入表不起作用
- vue.js - 无法将主题作为参数传递 Vue
- javascript - 单击时杀死所有正在运行的 JavaScript 函数
- oracle - Oracle PL/SQL 变量使用导致 SQL 开发人员出错
- python - 检查Python中的3d数组中是否存在2d数组?
- sql - SQL Server - 对子查询中的时间戳日期字段进行排序,然后格式化以供查看
- c# - Recipients.ResolveAll 一半失败
- react-native - 运行弹出时出错:错误:连接已禁用