I have a fragment layout 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 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 an 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 seems that ivIcon
is null, even though it's in the included layout. How can I reference this ImageView?
If you give an id to <include/>
tag it will override the id of parent included layout.
In your case most probably
android:id="@+id/ivRemoveData"
overrides the id of your imageView
. And the id ivIcon
could not be found.
You can change your xml like that:
<include
android:id="@+id/ivIcon"
layout="@layout/item_menu"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="16dp"
android:visibility="visible"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With