In my app I use NavController
with Fragments. In some fragments I need to access views on MainActivity
layout. I do that in this way:
val fab: FloatingActionButton = requireActivity().findViewById(R.id.fab)
This works properly as expected. However, one view does not want to be called and the findViewById()
returns null.
The layout structure is like this. In activity_main.xml
<androidx.drawerlayout.widget.DrawerLayout
<androidx.coordinatorlayout.widget.CoordinatorLayout
....>
<FrameLayout
android:id="@+id/frame"
.... />
<include
android:id="@+id/include"
layout="@layout/app_bar_main" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav"
.... />
</androidx.drawerlayout.widget.DrawerLayout>
is included app_bar_main.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout
....>
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
....>
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/collapsing"
....>
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
.... />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<include
android:id="@+id/content"
layout="@layout/content_main" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
.... />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
which includes content_main.xml
<androidx.core.widget.NestedScrollView
android:id="@+id/nested"
....>
<androidx.fragment.app.FragmentContainerView
android:id="@+id/host"
.... />
</androidx.core.widget.NestedScrollView>
The problem is, I need to access the NestedScrollView
and although all other views can be accessed, this one on the content_main.xml
cannot be accessed and returns null:
java.lang.NullPointerException: requireActivity().findViewById(R.id.nested) must not be null
EDIT:
class HomeFragment : Fragment() {
private lateinit var drawer: DrawerLayout
private lateinit var nested: NestedScrollView
private lateinit var fab: FloatingActionBar
private lateinit var bng: FragmentHomeBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
setHasOptionsMenu(true)
bng = FragmentHomeBinding.inflate(layoutInflater, container, false)
return bng.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
drawer = requireActivity().findViewById(R.id.drawer)
fab = requireActivity().findViewById(R.id.fab)
nested = requireActivity().findViewById(R.id.nested) // This line throws exception
.........
}
}
As you can see, I use viewBinding
to handle Fragment's Views
s.
I do not think that this might be problem.