Link from included layout

I have a mock snippet with the following include tag:

<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"/>

      

I need to use the method ivIcon.setImageResource()

.

My fragment class:

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)
    }
}

      

I am getting the error:

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)

      

It looks like it ivIcon

is null even though it is included in the included layout. How can I refer to this ImageView?

+3


source to share


1 answer


If you provide a tag ID <include/>

, it will override the parent layout ID.

In your case most probably

android:id="@+id/ivRemoveData"

      



overrides the id of your imageView

. And id ivIcon

could not be found.

You can change your xml like this:

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

      

+4


source







All Articles