包含布局的参考视图

时间:2017-06-06 16:45:31

标签: android kotlin-android-extensions

我有一个片段布局,其中包含以下include标记:

<include
    android:id="@+id/ivRemoveData"
    layout="@layout/item_menu"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_margin="16dp"
    android:visibility="visible"/>

item_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    android:id="@+id/ivIcon"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_centerInParent="true"

    android:visibility="gone"
    android:background="@drawable/not_passed_circle_level_item"
    android:clipChildren="false"
    android:clipToPadding="false"/>

我需要使用方法ivIcon.setImageResource()

我的片段类:

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_options.*
import kotlinx.android.synthetic.main.item_menu.view.*

class OptionsFragment : BaseFragment(), OptionsMVP.View
{
    override fun onCreateView(inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle?) : View?
    {
        val view = inflater.inflate(R.layout.fragment_options, container, false)
        return view
    }

    override fun onViewCreated(view : View?, savedInstanceState : Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)

        ivRemoveData.ivIcon.setImageResource(R.drawable.ic_delete)
    }
}

我收到错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
      at hobbajt.com.BubbleQuiz.Options.OptionsFragment.onViewCreated(OptionsFragment.kt:29)
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)

似乎ivIcon为空,即使它在包含的布局中也是如此。我该如何引用此ImageView?

1 个答案:

答案 0 :(得分:6)

如果您为<include/>标记提供了ID,它将覆盖父包含布局的ID。

在您的情况下most probably

android:id="@+id/ivRemoveData"

会覆盖您imageView的ID。并且无法找到身份ivIcon

您可以像这样更改您的xml:

<include
    android:id="@+id/ivIcon"
    layout="@layout/item_menu"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_margin="16dp"
    android:visibility="visible"/>