【问题标题】:Layout inside another layout is not accessible from the activity无法从活动访问另一个布局内的布局
【发布时间】:2019-05-08 09:38:49
【问题描述】:

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

但是当我尝试获取 constraintLayout 的 id 时,它返回 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>

【问题讨论】:

  • 确认您的ConstraintLayout 或terrace_collection_map.xml 以&lt;merge&gt; 标记开头和结尾,或者它有自己的根视图。
  • @Android :我已经编辑了我的答案,请检查,我没有使用 标签。
  • developer.android.com/training/improving-layouts/… 阅读此内容以使用 &lt;merge&gt; 标签,如果活动地图有 linearLayout 作为父标签。在 Terrace_collection_map 中使用 &lt;merge&gt; 标记作为父级之前的 ConstraintLayout。
  • 感谢这解决了我的问题,请将其添加为答案
  • 很高兴为您提供帮助。

标签: android performance android-layout android-constraintlayout


【解决方案1】:

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

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

所以使用&lt;merge&gt;标签,如果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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2013-11-23
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多