Android Kotlin: java.lang.IllegalStateException: title must not be null - android

I'm getting a IllegalStateException. Believe this is because my ProcessFragment.kt cannot identify id "title" for a TextView under fragment_process.xml.
How can I edit my code such that ProcessFragment.kt does not cause java.lang.IllegalStateException?
Thank you very much.
This is where the error occurs:
title.text = initProcess()
}
private fun initProcess(): String {
val python = Python.getInstance()
val pythonFile = python.getModule("ProcessFile")
return pythonFile.callAttr("Function1").toString()
}
ProcessFragment.kt
class ProcessFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
title.text = initProcess()
}
private fun initProcess(): String {
val python = Python.getInstance()
val pythonFile = python.getModule("ProcessFile")
return pythonFile.callAttr("Function1").toString()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_process, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ProcessFragment.
*/
// TODO: Rename and change types and number of parameters
#JvmStatic
fun newInstance(param1: String, param2: String) =
ProcessFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
fragment_process.xml
<?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"
tools:context="view.ProcessFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>

Related

How to use setOnClickListener in fragment

I ran into a problem, I put some buttons in my fragment and in the code file wanted to use them but I had a problem. Do you know some methods of how can I solve it? I use Kotlin
I tried a lot of variants on how to use setOnClickListener in fragments but it didn't work for me. My code looks like this:
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class WorkoutFragment : Fragment(),WorkoutAdapter.OnItemClickListener, WorkoutFragmentView {
private lateinit var presenter: WorkoutFragmentPresenter
private var param1: String? = null
private var param2: String? = 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? {
val v = inflater.inflate(R.layout.fragment_workout, container, false)
return v
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
WorkoutFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
private fun InitRecyclerView(v:View) {
val recyclerView = v.findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = WorkoutAdapter(WorkoutProvider.WorkoutList, this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
InitRecyclerView(view)
presenter = WorkoutFragmentPresenter(this)
}}
I answered this yesterday here.
Passing the fragment's view into the adapter isn't the best solution IMHO, it's better to pass a click lambda as demonstrated in the above example. In any case, all you have to do after that is just set an onClickListener in the adapter's items.

Android Studio ItemOnClickListener with ItemFilter and XML Problem

I have a question reagrding to RecyclerViews in Android Studio. I want to be able to start a newActivity on item Click and pass with somthing to be able to identify it in my Constants folder to get all the Informations about the Item. Position is not enought beacause I have implemented an Item Filter that changes positions of the itmes from filter to filter. Code is a bit messy im a newby and code isn't cleand up.
Fragment with RecyclerView:
This is the part that redirects:
override fun onItemClick(position: Int) {
val intent = Intent(context, ExerciseActivity::class.java)
Constants.PositionItemListener = position
intent.putExtra("Position", Constants.PositionItemListener)
startActivity(intent)
}
})
This is the whole code of fragment:
package ch.skimfit.skimfitapp
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import ch.skimfit.skimfitapp.databinding.ActivityMainBinding
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
private lateinit var adapter : RecyclerViewAdapterTraining
private lateinit var recyclerView: RecyclerView
private lateinit var exerciseList:ArrayList<Exercises>
private lateinit var tempArrayList:ArrayList<Exercises>
lateinit var exerciseImage:Array<Int>
lateinit var exerciseName:Array<String>
/**
* A simple [Fragment] subclass.
* Use the [home.newInstance] factory method to
* create an instance of this fragment.
*/
class home : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var content:ArrayList<Exercises>
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? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment home.
*/
// TODO: Rename and change types and number of parameters
#JvmStatic
fun newInstance(param1: String, param2: String) =
home().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dataInitialize()
setupFilter()
val layoutManager = LinearLayoutManager(context)
recyclerView = view.findViewById(R.id.rv_All)
recyclerView.layoutManager = layoutManager
recyclerView.setHasFixedSize(true)
var adapter = RecyclerViewAdapterTraining(tempArrayList)
recyclerView.adapter = adapter
adapter.setOnItemClickListener(object : RecyclerViewAdapterTraining.onItemClickListerner{
override fun onItemClick(position: Int) {
val intent = Intent(context, ExerciseActivity::class.java)
Constants.PositionItemListener = position
intent.putExtra("Position", Constants.PositionItemListener)
startActivity(intent)
}
})
}
private fun setupFilter() {
var rbAll: RadioButton? = view?.findViewById(R.id.rbAll)
var rbPush:RadioButton? = view?.findViewById(R.id.rbPush)
var rbPull:RadioButton? = view?.findViewById(R.id.rbPull)
var rbLeg:RadioButton? = view?.findViewById(R.id.rbLeg)
rbAll?.setOnClickListener{
tempArrayList.clear()
exerciseList.forEach {
if(it.Category.contains("exercise")){
tempArrayList.add(it)
}
}
recyclerView.adapter!!.notifyDataSetChanged()
}
rbPush?.setOnClickListener{
tempArrayList.clear()
exerciseList.forEach {
if(it.Category.contains("push")){
tempArrayList.add(it)
}
}
recyclerView.adapter!!.notifyDataSetChanged()
}
rbPull?.setOnClickListener{
tempArrayList.clear()
exerciseList.forEach {
if(it.Category.contains("pull")){
tempArrayList.add(it)
}
}
recyclerView.adapter!!.notifyDataSetChanged()
}
rbLeg?.setOnClickListener{
tempArrayList.clear()
exerciseList.forEach {
if(it.Category.contains("leg")){
tempArrayList.add(it)
}
}
recyclerView.adapter!!.notifyDataSetChanged()
}
}
private fun dataInitialize(){
exerciseList = Constants.getExerciseList()
tempArrayList = Constants.getExerciseList()
}
}
Constants:
package ch.skimfit.skimfitapp
object Constants {
var PositionItemListener: Int = 0
fun getExerciseList(): ArrayList<Exercises> {
val exerciseList = ArrayList<Exercises>()
val exe1 = Exercises(1,"Push exercise 1", R.drawable.training_recyclerview, "Test", "Test1", 0, 0, "pushexercise")
exerciseList.add(exe1)
val exe2 = Exercises(2,"Pull exercise 1", R.drawable.training_recyclerview, "Test", "Test2", 0, 0,"pullexercise")
exerciseList.add(exe2)
val exe3 = Exercises(3,"Pull exercise 2", R.drawable.training_recyclerview, "Test", "Test3", 0, 0, "pullexercise")
exerciseList.add(exe3)
val exe4 = Exercises(4,"Pull exercise 3", R.drawable.training_recyclerview, "Test", "Test4", 0, 0, "pullexercise")
exerciseList.add(exe4)
val exe5 = Exercises(5,"leg exercise 1", R.drawable.training_recyclerview, "Test", "Test5", 0, 0, "legexercise")
exerciseList.add(exe5)
val exe6 = Exercises(6,"leg exercise 2", R.drawable.training_recyclerview, "Test", "Test6", 0, 0, "legexercise")
exerciseList.add(exe6)
return exerciseList
}
}
And another Question:
Why is my Frame Layout in xml not Connecting to the complete Top if i constrain it to parent top
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/BackgroundMain"
android:paddingTop="?attr/actionBarSize">
<FrameLayout
android:id="#+id/fl_main"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/bottom_nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/BottomNavBarColor"
app:itemIconTint="#drawable/bottom_nav_bar_color_selected"
app:itemTextColor="#drawable/bottom_nav_bar_color_selected"
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>
I want it to be like the red line:
enter image description here
Found a Solution that works for me. Probably not the best one but working. Im now just passing in which Category the user is currently in to setup the same tempList in my receiving Activity. But still no solution for xml Problem.
Edit: Okay found the problem in xml just had a padding of ActionBarSize in the top.

Kotlin - interface not initialized when passing data between fragments

I am new to android development and making a simple To-do list app to get my bearings.
I have a fragment from my MainActivity that contains a list, called FragToDoList. I also have a class DialogAddToDo that extends DialogFragment to bring up a dialog to input your to do list item infomation. I am having trouble passing the data entered into DialogAddTodo back to the FragToDoList class to then display it in the list.
It is saying my interface is not initialized, and cant find a way to resolve this issue. Does anyone have some pointers?
class FragToDoList : Fragment(), DialogAddTodo.ToDoAddedListener {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private val toDoList: MutableList<ToDoItem>? = null
lateinit var adapter: ToDoAdapter
private lateinit var listViewItem: ListView
lateinit var mContext: Context
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
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? {
val view: View = inflater.inflate(R.layout.fragment_frag__to_do_list, container, false)
listViewItem = view.findViewById(R.id.listView)
//for showing items in list view
// adapter = ToDoAdapter(mContext, toDoList!!)
// listViewItem.adapter = adapter
val fab = view.findViewById<FloatingActionButton>(R.id.fabAddTask)
fab?.setOnClickListener {
showAddTaskDialog(childFragmentManager);
}
// Inflate the layout for this fragment
return view
}
private fun showAddTaskDialog(childFragmentManager:FragmentManager) {
var dialog = DialogAddTodo()
dialog.show(childFragmentManager,DialogAddTodo.TAG)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragTodoList.
*/
// TODO: Rename and change types and number of parameters
#JvmStatic
fun newInstance(param1: String, param2: String) =
FragToDoList().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
override fun onToDoAdded(item: ToDoItem) {
toast("added",mContext)
}
}
class DialogAddTodo : DialogFragment() {
interface ToDoAddedListener {
fun onToDoAdded(item: ToDoItem)
}
private lateinit var onTodoAdded: ToDoAddedListener
private val todoItemModel: TodoItemModel? =null
companion object {
const val TAG = "Dialog Add Task"
}
lateinit var mContext: Context
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.dialog_add_task, container, false)
var addBut = view.findViewById<Button>(R.id.butAddTaskDialog)
addBut.setOnClickListener()
{
val todoItemData = ToDoItem.createToDoItem()
var taskNameText =
view.findViewById<TextView>(R.id.editTextTaskName)
if (taskNameText != null)
todoItemData.itemDataText = taskNameText?.text.toString()
todoItemData.done = false
todoItemData.UID = getRandomString(Int.SIZE_BITS - 1)
// Frag_ToDoList().adapter.notifyDataSetChanged()
//b.setItem(todoItemData)
//todoItemModel.setItem(todoItemData)
onTodoAdded.onToDoAdded(todoItemData)
this.dismiss()
}
return view
}
}
You declared lateinit variable
private lateinit var onTodoAdded: ToDoAddedListener
however it remains uninitialized.
When uninitialized var accessed it throws an exception.
You need to assign variable for example using accessor:
var dialog = DialogAddTodo()
// Initialize listener
dialog.setListener(this)
dialog.show(childFragmentManager,DialogAddTodo.TAG)
In DialogAddTodo add following method:
fun setListener(onTodoAdded: ToDoAddedListener) {
this.onTodoAdded = onTodoAdded
}

Can Fragment act like MainActivity?

Project1
I have created a app that scans nearby wifidirect enabled devices whose UI was simple and had only one layout(activitymain.xml) and the code was in MainActivity.java & WifiDirectBroadcastReceiver. (Code can be found here: Can't find nearby WiFi- Direct devices showing "No Device Found!")
Project2
Now, I want to use Tablayout(custom not from default) which contains 2 tabs so I have to use 2 fragments.
Where should I place the code that was in MainActivity(project1)?
should I copy to fragment1 or MainActivity(Project2)
You have to copy the code of MainActivity (project1) to fragment of the tabbed layout. And then configure the SectionPagerAdapter like below.
Also you have to change some code of your MainActivity so that it gets fitted into the fragment.
private val TAB_TITLES = arrayOf(
R.string.tab_text_1,
R.string.tab_text_2
)
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter(private val context: Context, fm: FragmentManager)
: FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
var fragment: Fragment? = null
when (position) {
0 -> fragment = Fragment1("f1","f1")
1 -> fragment = Fragment2("f2","f2")
}
return fragment!!
}
override fun getPageTitle(position: Int): CharSequence? {
return context.resources.getString(TAB_TITLES[position])
}
override fun getCount(): Int {
// Show 2 total pages.
return 2
}
}
You can create fragments like this:
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class Fragment1 : Fragment() {
private var param1: String? = null
private var param2: String? = null
private var _binding: Fragment1Binding? = null
private val binding get() = _binding!!
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 {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onPause() {
super.onPause()
}
override fun onResume() {
super.onResume()
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
HomeFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
You can make Fragment2 like this and attach this to your tabbed layout.

How to Set SetOnClickListener for a button in a fragment of NavigationDrawerActivity? in Kotlin

Hello everyone I made a Drawer Activity but in my fragment i want a button So that when i press button this Should change text to Hi or Hello, but i don't where the code should be present when i try to add code in FirstFragemt.kt file it throw an error ,Please Help me Thank you
Here is My MainActivity :
class MainActivity : AppCompatActivity(),FirstFragment.OnFragmentInteractionListener,SecondFragment.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.first_activity -> {
title = "Fragment One"
val fragment = FirstFragment()
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragmentID, fragment, "FragmentOne") //create first framelayout with id fram in the activity where fragments will be displayed
fragmentTransaction.commit() // Handle the camera action
}
R.id.second_activity -> {
title = "Fragment Second"
val fragment = SecondFragment()
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragmentID, fragment, "FragmentSecond") //create first framelayout with id fram in the activity where fragments will be displayed
fragmentTransaction.commit()
}
R.id.nav_share -> {
}
R.id.nav_exit -> {
System.exit(0)
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
override fun onFragmentInteraction(uri: Uri) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
} }
Here is My FirstFragent file :
`
class FirstFragment : Fragment() {
private var mParam1: String? = null
private var mParam2: String? = null
private var mListener: OnFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
mParam1 = arguments.getString(ARG_PARAM1)
mParam2 = arguments.getString(ARG_PARAM2)
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}
// TODO: Rename method, update argument and hook method into UI event
fun onButtonPressed(uri: Uri) {
if (mListener != null) {
mListener!!.onFragmentInteraction(uri)
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
mListener = context
} else {
throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(uri: Uri)
}
companion object {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private val ARG_PARAM1 = "param1"
private val ARG_PARAM2 = "param2"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FirstFragment.
*/
// TODO: Rename and change types and number of parameters
fun newInstance(param1: String, param2: String): FirstFragment {
val fragment = FirstFragment()
val args = Bundle()
args.putString(ARG_PARAM1, param1)
args.putString(ARG_PARAM2, param2)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
Here is my FirstFragment layout xml file :
<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"
tools:context="com.a3.aakap.ftrial.FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/button"
android:layout_width="200sp"
android:layout_height="50sp"
android:text="Click me !!"
android:layout_marginLeft="100dp"
android:layout_marginRight="100dp"
android:layout_gravity="center"/>
</FrameLayout>
create a overide of onViewCreated in those Fragment Here is a code :
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button.setOnClickListener{
text.setText("Hello")
}
}
So, what you're missing is getting hold on the view of your fragment, and the views inside it (mainly your button and your TextView), and doing stuff on them.
In your FirstFragment.kt :
private lateinit var mTextView: TextView
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater!!.inflate(R.layout.fragment_first, container, false)
mTextView = findViewById(R.id.text)
findViewById<Button>(R.id.button).setOnClickListener { mTextView.text = "Hi" }
return view
}
class FirstFragment : Fragment() {
private var ctx: Context? = null
private var self: View? = null
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
ctx = container?.context
self = LayoutInflater.from(ctx).inflate(R.layout.fragment_start, container, false)
val bDaButton = self?.findViewById<Button>(R.id.bDaButton)
bDaButton?.setOnClickListener {
Toast.makeText(ctx, "button works!", Toast.LENGTH_SHORT).show()
}
return self
}
}
<Button
android:id="#+id/bDaButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Work!"/>

Categories

Resources