I'm competely new to Kotlin trying to build an app following a tutorial, but trying to navigate to fragment it completely crashes.
This what I got after I tried to navigate to the other fragment:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.application, PID: 10385
java.lang.IllegalArgumentException: No view found for id 0x7f08005a (com.example.application:id/container) for fragment Create{b25f2a9 (ffc51d9a-d9bb-425d-a264-1a68c77134fb) id=0x7f08005a}
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
This how I try to navigate to the fragment.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottomNavigation: BottomNavigationView = findViewById(R.id.nav_view)
bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.menu_home -> {
val fragment_main = Main.newInstance()
openFragment(fragment_main)
return#OnNavigationItemSelectedListener true
}
R.id.menu_create -> {
val fragment_create = Create.newInstance()
openFragment(fragment_create)
return#OnNavigationItemSelectedListener true
}
R.id.menu_your -> {
val fragment_your_articles = YourArticles.newInstance()
openFragment(fragment_your_articles)
return#OnNavigationItemSelectedListener true
}
}
false
}
private fun openFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
}
One of the Fragment class
class Create : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_create, container, false)
companion object {
fun newInstance(): Create = Create()
}
}
I want to know what mistake did I made to cause the crash and how can I fix it.
This xml file of one of the fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView4"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="200dp"
android:text="#string/create_screen"
/>
</LinearLayout>
The id passed into FragmentTransaction.add(), in your case R.id.fragment_create, must be a child of the layout specified in setContentView().
For help: A view is a child of another view if it is declared inside of the parent view in the XML. ie. a TextView inside of a RelativeLayout is a child of the RelativeLayout
As I said I'm completely new to Kotlin and I'm still getting used to how and what must be displayed if I'm trying to use Fragment. I forgot that I need FrameLayout to my main_activity.xml
As I added FrameLayout in my main_activity.xml file it's started working as I wanted.
This line in your openFragment function
transaction.replace(R.id.container, fragment)
tells it to place the fragment in the ViewGroup with the ID "container". But your layout does not contain a ViewGroup with this ID. Check your activity_main.xml layout and make sure it has one with that ID.
Related
I have the following code:
activity_reminders.xml
<androidx.constraintlayout.widget.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="match_parent"
android:layout_height="match_parent"
tools:context=".locationreminders.RemindersActivity">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
ReminderActivity.kt
class RemindersActivity : AppCompatActivity() {
private lateinit var binding: ActivityRemindersBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRemindersBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
(binding.navHostFragment as NavHostFragment).navController.popBackStack()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
binding.navHostFragment in unresolved and i don't understand why, if i change the type of view in anything differnt then "fragment" the view binding works.
Is possible to use view vbinding for a fragment inside another view?
I found the following as a workaround solution to get the fragment.
val navHostFragment = findNavController(R.id.nav_host_fragment)
navHostFragment.popBackStack()
I think that is not possible to use view binding with a <fragment> because fragment is not a descendent of View.
Instead of:
(binding.navHostFragment as NavHostFragment).navController.popBackStack()
Use the following code:
(supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment).navController.popBackStack()
I have one activity and few fragments. I set up my activity with NavController and navigation graph like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_activity_main) as NavHostFragment
navController = navHostFragment.findNavController()
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
In this navigation graph I take care of splash screen, login, register fragment and going to main fragment which has a BottomNavigationView with two sub fragments.
I made a menu for bottomNavView fragments and made a graph for them, menu id's match with bottom nav graph id's.
My layout looks like this:
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#+id/bottom_Navigation_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/bottom_view_nav_graph" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_Navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
In main fragment I am trying to set up bottom nav view with navigation graph like this:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val appCompat = requireActivity() as AppCompatActivity
val navHostFragment = appCompat.supportFragmentManager.findFragmentById(R.id.nav_host_fragment_main) as NavHostFragment
val navController = navHostFragment.findNavController()
binding.bottomNavigationView.setupWithNavController(navController)
}
However I keep getting this exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ak.chatter, PID: 1937
java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment
at com.ak.chatter.ui.main.MainFragment.onViewCreated(MainFragment.kt:34)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:900)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
java.lang.NullPointerException: null cannot be cast to non-null type
androidx.navigation.fragment.NavHostFragment
You try to cast a null to a non-null.
The null is got from appCompat.supportFragmentManager.findFragmentById(R.id.nav_host_fragment_main) statement.
Because the supportFragmentManager is used as the fragment manager of fragments that are hosted by a fragment. Although the supportFragmentManager should manage fragments that are hosted by an activity.
Whereas the childFragmentManager should be used instead to manage fragments that are hosted by another fragment.
So, to solve this replace supportFragmentManager with childFragmentManager in the main fragment class:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val appCompat = requireActivity() as AppCompatActivity
val navHostFragment = appCompat.childFragmentManager.findFragmentById(R.id.nav_host_fragment_main) as NavHostFragment
val navController = navHostFragment.findNavController()
binding.bottomNavigationView.setupWithNavController(navController)
}
This is supposedly a simple thing to achieve but for some reason I can't get it to work. I'm using SDK 30 emulator to test. Basically the new fragment appears but there is zero animation whatsoever. If I add a Fade() transition it works only for the fade transition. I've tried setting sharedElement callback but the methods are called only intermittently. Basically it's a simple image. You click on it and the new fragment appears. Click it again and it's gone.
Layout snippet of activity containing image
<FrameLayout
android:id="#+id/container_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
>
<ImageView
android:id="#+id/image_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_error_24"
android:transitionName="image"
android:layout_gravity="center"
/>
</FrameLayout>
Logic to open image fragment
override fun openImageFragment(imageView: ImageView) {
val fragment = ImageFragment()
fragment.image = imageView.drawable
fragment.arguments = Bundle().also {
it.putString(ImageFragment.KEY_TRANSITION, imageView.transitionName)
}
// fragment.enterTransition = Fade()
// fragment.exitTransition = Fade()
supportFragmentManager
.beginTransaction()
.setReorderingAllowed(true)
.addSharedElement(imageView, imageView.transitionName)
.replace(R.id.container_test, fragment)
.commitNow()
}
Image fragment layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
/>
</FrameLayout>
ImageFragment
class ImageFragment : Fragment() {
private lateinit var binding: FragmentImageBinding
var image: Drawable?= null
companion object {
const val KEY_TRANSITION = "TRANSITION"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val transition = TransitionInflater.from(requireContext()).inflateTransition(android.R.transition.move)
sharedElementEnterTransition = transition
sharedElementReturnTransition = transition
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentImageBinding.inflate(inflater, container, false)
binding.imageView.transitionName = arguments?.getString(KEY_TRANSITION)
binding.imageView.setImageDrawable(image)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.setOnClickListener {
requireActivity().supportFragmentManager
.beginTransaction()
.remove(this)
.commit()
}
}
}
After much trial and error, I figured out the reason.
My initial fragment was placed statically on the XML, which prevented the fragment manager from replacing it. By using the layout inspector I figured out that the new fragment was placed right below the first one.
Basically the solution is to add the first fragment programmatically so the fragment manager can manipulate it.
Hi I'm working with here SDK for android and I keep getting this error
my project has a navigation drawer and I'm trying to have a map in one of its fragments with here SDK
here are my XML and Kotlin code and the error
my error :
java.lang.ClassCastException: com.here.android.mpa.mapping.MapView cannot be cast to com.here.android.mpa.mapping.AndroidXMapFragment
at com.example.pplin_mobilite.ui.Passager.PassagerFragment.onActivityCreated(PassagerFragment.kt:22)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2717)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1188)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6758)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
my kotlin class :
class PassagerFragment : Fragment() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// Search for the Map Fragment
val mapFragment = map_frag as AndroidXMapFragment
// initialize the Map Fragment and
// retrieve the map that is associated to the fragment
mapFragment.init { error ->
if (error == OnEngineInitListener.Error.NONE) {
// now the map is ready to be used
mapFragment.map
// ...
} else {
println("ERROR: Cannot initialize AndroidXMapFragment")
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_notifications,container,false)
}
}
and my xml :
<fragment
class="com.here.android.mpa.mapping.AndroidXMapFragment"
android:id="#+id/map_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
If you are using the fragment from Here documentation, as it looks like you are, and putting it inside another fragment, you should use:
val mapfragment = childFragmentManager.findFragmentById(R.id.mapfragment) as AndroidXMapFragment
Then you find the fragment and not the View (since it is not a view), because, if you inspect mapfragment, it already extends Fragment()
Try using the supportFragmentManager:
val mapfragment = supportFragmentManager.findFragmentById(R.id.map_frag) as AndroidXMapFragment?
This is my first question on Stack Overflow, so apologies in advance if I'm asking in an improper way.
I'm trying to create a basic app in Kotlin, wherein I have a hamburger menu with some fragments in it. When the user clicks on the HomeFragment, I want to display a welcome message with his name (stored in a Shared Preferences object).
However, each time I click on the menu button to open the fragment, it crashes - even if I remove the whole username/shared prefs thing and just try to set some plain text.
Here is my HomeFragment.kt file:
package com.urmilshroff.kotlindemo
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_home.*
private const val ARG_PARAM1="param1"
private const val ARG_PARAM2="param2"
class HomeFragment:Fragment()
{
private var param1:String?=null
private var param2:String?=null
private var listener:OnFragmentInteractionListener?=null
override fun onCreate(savedInstanceState:Bundle?)
{
super.onCreate(savedInstanceState)
arguments?.let {
param1=it.getString(ARG_PARAM1)
param2=it.getString(ARG_PARAM2)
}
}
override fun onCreateView(inflater:LayoutInflater,container:ViewGroup?,
savedInstanceState:Bundle?):View?
{
super.onCreate(savedInstanceState)
val username=SharedPrefObj.getUsername(this.activity!!)
textViewHello.text="Hi there, $username!"
return inflater.inflate(R.layout.fragment_home,container,false)
}
fun onButtonPressed(uri:Uri)
{
listener?.onFragmentInteraction(uri)
}
override fun onAttach(context:Context)
{
super.onAttach(context)
if(context is OnFragmentInteractionListener)
{
listener=context
}
else
{
throw RuntimeException(context.toString()+" must implement OnFragmentInteractionListener")
}
}
override fun onDetach()
{
super.onDetach()
listener=null
}
interface OnFragmentInteractionListener
{
fun onFragmentInteraction(uri:Uri)
}
companion object
{
#JvmStatic
fun newInstance()=
HomeFragment().apply {
arguments=Bundle().apply {
putString(ARG_PARAM1,param1)
putString(ARG_PARAM2,param2)
}
}
}
}
My fragment_home.xml, just in case:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".HomeFragment">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewHello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:fontFamily="monospace"
android:textAlignment="center"
android:textColor="#color/colorAccent"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/textViewDesc"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.993" />
<TextView
android:id="#+id/textViewDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="240dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:fontFamily="monospace"
android:text="#string/text_view_desc"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
Crash log:
09-17 00:19:24.968 25279-25279/com.urmilshroff.kotlindemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.urmilshroff.kotlindemo, PID: 25279
java.lang.IllegalStateException: textViewHello must not be null
at com.urmilshroff.kotlindemo.HomeFragment.onCreateView(HomeFragment.kt:37)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
It says that textViewHello must not be null, so I tried making it nullable yet it crashes. Not sure what's wrong. Any help is much appreciated, thanks!
textViewHello has not been initialized.
Initialise it like this:
val rootView = inflater.inflate(R.layout.fragment_home,container,false)
val textViewHello: TextView = rootView.findViewById(R.id.textViewHello) as TextView
Add the above line before setting text on textview
final onCreateView will look like this:
super.onCreate(savedInstanceState)
val rootView = inflater.inflate(R.layout.fragment_home,container,false)
val username=SharedPrefObj.getUsername(this.activity!!)
val textViewHello: TextView = rootView.findViewById(R.id.textViewHello) as TextView
textViewHello.text="Hi there, $username!"
return rootView;
You are using Kotlin Android Extentions in your project, so no need to call findViewById method anymore.
All you need to do is change your code to:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
super.onCreate(savedInstanceState)
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val username = SharedPrefObj.getUsername(this.activity!!)
textViewHello.text = "Hi there, $username!"
}
put below line in onViewCreated method. You need to override that method.
textViewHello.text="Hi there, $username!"
this will set the textview after it has been initiated in onCreateView
You need use it in onViewCreated.
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.qr_my_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init()
}
private fun init() {
setQRCode()
initToolbar()
clickEvents()
}
You are trying to call method setText, but your TextView object actually is null. You need to initialize.
Before set text, you should make some step.
1. Inflate view in variable
val view = inflater.inflate(R.layout.fragment_home,container,false)
2. Find and connect xml object with class variable
val textView: TextView = view.findViewById(R.id.textViewHello)
3. Now, you can call setText
textView.setText("Example text")
Just modify your onCreateView method
val view = inflater.inflate(R.layout.fragment_home,container,false)
val textView: TextView = view.findViewById(R.id.textViewHello)
textView.setText("Example text")