首页 > 解决方案 > 无法从活动访问另一个布局内的布局

问题描述

我有多个按层次顺序定义的布局,问题是当我尝试访问在内部布局中定义的项目时,它给了我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>

标签: androidperformanceandroid-layoutandroid-constraintlayout

解决方案


尝试添加<merge /> 标记,以帮助您在将一个布局包含在另一个布局中时消除视图层次结构中的冗余视图组。

例如,如果您的主布局是垂直LinearLayout的,其中两个连续的视图可以在多个布局中重复使用layout,那么放置两个视图的可重复使用的视图需要它自己的根视图。

所以使用<merge>标签,如果activity_map.xmlLinearLayout作为父标签。然后更改您的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


推荐阅读