Home > other >  How can I access a TextView declared in XML within my Fragment?
How can I access a TextView declared in XML within my Fragment?

Time:03-09

Here is the kotlin file of the fragment:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle? ): View? {
    
        val view = inflater.inflate(R.layout.fragment_blank, container, false)
    
        view.textView1 <- Here is the problem
    
        return view
    }

Down here is xml file of the fragment. I hope it's all right...

<?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"
    android:background="@color/purple_200"
    tools:context=".BlankFragment">

    <TextView
        android:id="@ id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="1"
        android:gravity="center"
        android:textSize="80sp" />
</FrameLayout>

CodePudding user response:

textView = findViewById(R.id.yourId);

and next you can use it

CodePudding user response:

Actually findViewById() is not available on the Fragment class.

However, you can use inflated view to access the findViewById() as shown on this example.

class MyFragment : Fragment() {

    lateinit var textView: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_my, container, false)
        
        //use view to access findViewById() method
        textView = view.findViewById(R.id.textView1)
        textView.text = "Test 1"
        return view
    }
}

That said the recommended way would be to use Databinding or View Binding

  • Related