NullPointerException on RecyclerView setLayoutManager - android

I have faced the problem that my application will keep stopping when clicking search page fragments. I do not understand why this problem will happen? I directly used my other success code in another fragment but in this fragment suddenly appear this problem. Can somebody help me? Thank you for your help!!
My problem error :
java.lang.NullPointerException: Attempt to invoke virtual method
'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)'
on a null object reference at com.example.assignment_mad.Search_Page_Fragment.onViewCreated(Search_Page_Fragment.kt:153)
My main frgment ( Search_Page_Fragment ) :
package com.example.assignment_mad
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.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_notification_.*
class Search_Page_Fragment : Fragment() {
private lateinit var newRecyclerView: RecyclerView
private lateinit var newArrayList: ArrayList<Company_Search>
private lateinit var tempArrayList: ArrayList<Company_Search>
lateinit var imageId:Array<Int>
lateinit var job_name:Array<String>
lateinit var saveicon:Array<Int>
lateinit var company_name:Array<String>
lateinit var place:Array<String>
lateinit var salary:Array<String>
lateinit var news:Array<String>
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<Search_Page_Adapter.MyViewHolder>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var views =inflater.inflate(R.layout.fragment_search__page_, container, false)
newRecyclerView=views.findViewById(R.id.recyclerView_Search)
// Inflate the layout for this fragment
return views
}
override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {
imageId= arrayOf(
R.drawable.company_logo_1,
R.drawable.company_logo_2,
R.drawable.company_logo_3,
R.drawable.company_logo_4,
R.drawable.company_logo_5,
R.drawable.company_logo_6,
R.drawable.company_logo_7,
R.drawable.company_logo_8,
R.drawable.company_logo_9,
R.drawable.company_logo_10
)
job_name= arrayOf(
"Engineer",
"Computer",
"Coder",
"Teacher",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer"
)
saveicon= arrayOf(
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24
)
company_name= arrayOf(
"Phonix Sdn Bhd",
"Computer Sdn Bhd",
"Coder",
"Teacher",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer"
)
place= arrayOf(
"Kuala Lumpur",
"Kuala Lumpur",
"Selangor",
"Rimbunan",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur"
)
salary= arrayOf(
"RM3000",
"RM4000",
"RM3500",
"RM2000",
"RM1000",
"RM3000",
"RM3000",
"RM3000",
"RM3000",
"RM3000",
)
news= arrayOf(
getString(R.string.news_a),
getString(R.string.news_b),
getString(R.string.news_c),
getString(R.string.news_d),
getString(R.string.news_e),
getString(R.string.news_f),
getString(R.string.news_g),
getString(R.string.news_h),
getString(R.string.news_i),
getString(R.string.news_j)
)
newArrayList= arrayListOf<Company_Search>()
tempArrayList= arrayListOf<Company_Search>()
getUserdata()
super.onViewCreated(itemView, savedInstanceState)
newRecyclerView.apply {
layoutManager= LinearLayoutManager(activity)
newRecyclerView.setHasFixedSize(true)
}
recyclerView.apply {
// set a LinearLayoutManager to handle Android
// RecyclerView behavior
layoutManager= LinearLayoutManager(activity)
// set the custom adapter to the RecyclerView
adapter = Search_Page_Adapter(newArrayList)
}
}
private fun getUserdata() {
for (i in imageId.indices){
val companySearch=Company_Search(imageId[i],job_name[i],saveicon[i],company_name[i],place[i],salary[i])
newArrayList.add(companySearch)
}
// tempArrayList.addAll(newArrayList)
//
// val adapter = Notification_Fragment(tempArrayList)
var adapter=Search_Page_Adapter(newArrayList)
newRecyclerView.adapter=adapter
adapter.setOnItemClickListener(object :Search_Page_Adapter.onItemClickListener{
override fun onItemClick(position: Int) {
Toast.makeText(context,"You clicked in item no . $position",Toast.LENGTH_SHORT).show()
val intent= Intent(context,Search_Page_Detail::class.java)
intent.putExtra("name",newArrayList[position].job_name)
intent.putExtra("imageId",newArrayList[position].titleImage)
intent.putExtra("news",news[position])
startActivity(intent)
}
})
}
}
The page adapter :
package com.example.assignment_mad
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.imageview.ShapeableImageView
class Search_Page_Adapter(private val companysList:ArrayList<Company_Search>):RecyclerView.Adapter<Search_Page_Adapter.MyViewHolder>() {
private var mListener:onItemClickListener?=null
interface onItemClickListener{
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener){
mListener=listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView=LayoutInflater.from(parent.context).inflate(R.layout.list_item_search,parent,false)
return MyViewHolder(itemView,mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem=companysList[position]
holder.titleImage.setImageResource(currentItem.titleImage)
holder.job_name.text=currentItem.job_name
holder.save_icon.setImageResource(currentItem.save_icon)
holder.company_name.text=currentItem.company_name
holder.place.text=currentItem.place
holder.salary.text=currentItem.salary
}
override fun getItemCount(): Int {
return companysList.size
}
//to insert the post detail
class MyViewHolder(itemView: View,listener: onItemClickListener?):RecyclerView.ViewHolder(itemView){
val titleImage:ShapeableImageView=itemView.findViewById(R.id.title_image2)
val job_name:TextView=itemView.findViewById(R.id.job_name)
val save_icon:ShapeableImageView=itemView.findViewById(R.id.save_icon)
val company_name:TextView=itemView.findViewById(R.id.company_name)
val place:TextView=itemView.findViewById(R.id.detail_place)
val salary:TextView=itemView.findViewById(R.id.detail_salary)
init {
itemView.setOnClickListener{
listener?.onItemClick(adapterPosition)
}
}
}
}
The xml file for Search_Page_Fragment :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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"
android:background="#color/white"
tools:context=".Search_Page_Fragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search Job"
android:inputType="text"
android:minHeight="48dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="#+id/place_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Area, City or Town"
android:textSize="16sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/search_bar"
app:layout_constraintStart_toStartOf="parent"/>
<Spinner
android:id="#+id/spinner_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/place_name" />
<TextView
android:id="#+id/job_specialize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Job Specialize"
android:textSize="16sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/search_bar"
app:layout_constraintEnd_toEndOf="parent" />
<Spinner
android:id="#+id/spinner_place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dp"
app:layout_constraintTop_toBottomOf="#+id/job_specialize"
app:layout_constraintEnd_toEndOf="parent"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_Search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="108dp"
app:layout_constraintTop_toBottomOf="#+id/spinner_job"
tools:layout_editor_absoluteX="-16dp"
tools:listitem="#layout/list_item_search" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
The list_item_search_xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="8dp">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/title_image2"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shapeAppearanceOverlay="#style/RoundCorner"
android:src="#drawable/company_logo_1"/>
<TextView
android:id="#+id/job_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/blue"
android:text="Gradute Engineer"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_image2"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/save_icon"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_image2"
android:layout_marginEnd="32dp"
app:shapeAppearanceOverlay="#style/RoundCorner"
android:src="#drawable/ic_baseline_bookmark_added_24"/>
<TextView
android:id="#+id/company_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Neric Compat"
android:textSize="18sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/job_name"/>
<TextView
android:id="#+id/detail_place"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Petaling Jaya"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/company_name"/>
<TextView
android:id="#+id/detail_salary"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="MYR 3,700 - 4,300 /Month"
android:textSize="16sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/detail_place"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_margin="8dp"
style="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/detail_salary"
android:background="#color/underline"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Your NullPointerException indicates that when this line of code is reached...
layoutManager= LinearLayoutManager(activity)
...that your newRecyclerView is null. Are you sure that you have the right resource ID here when you attempt to set it?
newRecyclerView=views.findViewById(R.id.recyclerView_Search)
Try using the debugger and set a breakpoint on these two lines to confirm is newRecyclerView is indeed null.

You must assign the RecyclerView a LayoutManager. Since you have both of them, place this line as the last statement of recyclerView.apply { … } block(s):
setLayoutManager(layoutManager)
// ↑↑↑↑↑↑↑↑↑↑↑↑↑
// Your LayoutManager

Related

CopytoClipboard not working in Adapter to show in recyclerview

I have a recyclerview with adapter (to show external strings)and I'm trying to click a button "copy" so that it copies the strings in view to the clipboard.
CardLayout.xml Button to use as copy button is android:id="#+id/copyactivity"
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="0dp"
app:cardElevation="0dp"
app:cardMaxElevation="3dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
tools:context="ui.CardLayout">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/idActivityName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="14dp"
android:layout_marginRight="10dp"
android:text="#string/placeholdertasktitle"
android:textColor="#color/black"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/idActivityDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/idActivityName"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="30dp"
android:drawablePadding="2dp"
android:text="#string/let_s_get_started_creating_a_photo_album_for_you_so_you_can_share_with_the_kids_in_the_near_future"
android:textColor="#color/black"
android:textSize="15sp"
tools:ignore="UnknownId" />
<View
android:id="#+id/divider"
android:layout_width="380dp"
android:layout_height="2dp"
android:layout_below="#id/idActivityDescription"
android:layout_alignStart="#id/idActivityName"
android:layout_centerHorizontal="false"
android:layout_centerVertical="false"
android:background="#EDEDED" />
<Button
android:id="#+id/saves"
style="#style/cardbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/divider"
android:layout_alignStart="#id/idActivityName"
android:background="#drawable/cardbutton"
android:contentDescription="#string/saves"
android:stateListAnimator="#null"
android:text="Save"
android:textAlignment="textStart"
android:textColor="#595959"
android:textSize="12sp"
app:icon="#drawable/ic_saves_blank"
app:iconGravity="textStart"
app:iconTint="#595959" />
<Button
android:id="#+id/calendar"
style="#style/cardbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/divider"
android:layout_marginStart="35dp"
android:layout_marginEnd="35dp"
android:layout_toStartOf="#+id/copyactivity"
android:layout_toEndOf="#id/saves"
android:background="#drawable/cardbutton"
android:contentDescription="#string/saves"
android:stateListAnimator="#null"
android:text="#string/calendar"
android:textAlignment="textStart"
android:textColor="#595959"
android:textSize="12sp"
app:icon="#drawable/ic_calendar"
app:iconGravity="textStart"
app:iconTint="#595959" />
<Button
android:id="#+id/copyactivity"
style="#style/cardbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/divider"
android:layout_alignEnd="#id/divider"
android:background="#drawable/cardbutton"
android:contentDescription="#string/saves"
android:stateListAnimator="#null"
android:text="#string/copy"
android:textAlignment="textStart"
android:textColor="#595959"
android:textSize="12sp"
app:icon="#drawable/ic_copytext"
app:iconGravity="textStart"
app:iconTint="#595959" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
And this is my TaskAdapter.kt
package com.example.what2do_v6.Adapter
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.RecyclerView
import com.example.what2do_v6.Model.TaskResponse
import com.example.what2do_v6.R
import com.example.what2do_v6.Repository.TaskRepository
import com.example.what2do_v6.databinding.CardLayoutBinding
import com.example.what2do_v6.ui.CardLayout
import android.content.Context as ContentContext
class TaskAdapter: RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = CardLayoutBinding.inflate(layoutInflater, parent, false)
return TaskViewHolder(binding)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
holder.bind(TaskRepository.list[position])
}
override fun getItemCount(): Int {
return TaskRepository.list.size
}
class TaskViewHolder(private val binding: CardLayoutBinding) : RecyclerView.ViewHolder(binding.root){
var bCopyText: Button? = null
fun bind(task: TaskResponse) {
binding.idActivityName.text = task.title
binding.idActivityDescription.text = task.description
bCopyText = findViewById<View>(R.id.copyactivity) as Button
val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
bCopyText!!.setOnClickListener {
val clipData = ClipData.newPlainText("", task.description,)
clipboardManager.setPrimaryClip(clipData)
Toast.makeText(RecyclerView, "message...", Toast.LENGTH_SHORT).show()
}
}
private fun getSystemService(clipboardService: String): Any {
}
}
}
There are two lines in my code that are throwing up problems:
bCopyText = findViewById<View>(R.id.copyactivity) as Button
and
Toast.makeText(RecyclerView, "message...", Toast.LENGTH_SHORT).show()
I've tried different variances of the two above lines and research many articles on StackOverflow but with no winner, can anyone help?
Managed to get this working utilising help from Gobu:
class TaskViewHolder(private val binding: CardLayoutBinding) : RecyclerView.ViewHolder(binding.root){
fun bind(task: TaskResponse) {
binding.idActivityName.text = task.title
binding.idActivityDescription.text = task.description
binding.copyactivity
binding.copyactivity.setOnClickListener {
val clipboardManager = itemView.context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText("", task.title +"\n\n" + task.description)
clipboardManager.setPrimaryClip(clipData)
Toast.makeText(itemView.context, "Activity copied to clipboard", Toast.LENGTH_SHORT).show()
}
}
First of all, if you're using ViewBinding, why would you declare a variable for your button? Just get it from the binding.
Second, it's giving you an error, because you're making sure (!!) that the button you declare isn't null, but most likely it is, because you're trying to get the ID of a view you don't have.
Third, RecyclerView is not a context, if you are using ViewBinding, you get the context from binding.root.context

Implementing ViewModel to seekbars and are stuck

I am currently making a loan app where the user can use seekbar for how large the rent is going to be int how many years they want to pay down the loan.
We are supposed to use viewmodel, live data and databinding to store data between fragments. Iam stuck when it comes to use viewmodel to find progress int inside the seekbar.
I am not sure how to call the startPoint and endPoint that is going to determinate the "var" I need to calculate the loan plan in the next fragment?
Please look past that the file contains comments since it older code I am rewriting.
Thanks for the help.
AnnuitetFragment.kt:
package com.example.lnognedbetalingsplan
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.lnognedbetalingsplan.databinding.FragmentAnnuitetBinding
import com.example.lnognedbetalingsplan.viewmodel.AnnuitetViewModel
class AnnuitetFragment : Fragment() {
private var _binding: FragmentAnnuitetBinding? = null
private val binding get() = _binding!!
private lateinit var viewModel: AnnuitetViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
_binding = FragmentAnnuitetBinding.inflate(inflater, container, false)
return binding.root
}
val viewAnnuitet = inflater.inflate(R.layout.fragment_annuitet, container, false)
val buttonTilbake = viewAnnuitet.findViewById<Button>(R.id.tilbakeTilVelkommen)
val buttonBeregn = viewAnnuitet.findViewById<Button>(R.id.BeregnLaanAnnuitet)
val seekbarRenter = viewAnnuitet.findViewById<SeekBar>(R.id.RenterAnnSeekBar)
val seekBarAar = viewAnnuitet.findViewById<SeekBar>(R.id.AarSerieSeekBar)
val renterTall = viewAnnuitet.findViewById<TextView>(R.id.RenterTall)
val aarTall = viewAnnuitet.findViewById<TextView>(R.id.AarTall)
// var startPoint = 0
// var endPoint = 0
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tilbakeTilVelkommen.setOnClickListener {
findNavController().navigate(R.id.action_velkommenFragment_to_annuitetFragment)
}
binding.BeregnLaanAnnuitet.setOnClickListener {
findNavController().navigate(R.id.action_velkommenFragment_to_serieFragment)
}
binding.RenterAnnSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
binding.RenterTall.text = progress.toString()
}
override fun onStartTrackingTouch(p0: SeekBar?) {
if (p0 != null){
viewModel =
}
}
override fun onStopTrackingTouch(p0: SeekBar?) {
TODO("Not yet implemented")
}
}
// seekbarRenter.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
// override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
// RenterTall
// }
//
// override fun onStartTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// startPoint = seekBar.progress
// }
//
// }
//
// override fun onStopTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// endPoint = seekBar.progress
// }
// }
// })
//
// seekBarAar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
// override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
// aarTall.text = progress.toString()
// }
//
// override fun onStartTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// startPoint = seekBar.progress
// }
//
// }
//
// override fun onStopTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// endPoint = seekBar.progress
// }
// }
// })
return viewAnnuitet
}
}
fragment_annuitet.xml:
<?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:layout_width="match_parent"
android:layout_height="match_parent">
<SeekBar
android:id="#+id/RenterAnnSeekBar"
android:layout_width="300dp"
android:layout_height="30dp"
android:max="50"
android:min="0"
android:progress="5"
app:layout_constraintBottom_toTopOf="#+id/AarSerieSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.306"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.84" />
<SeekBar
android:id="#+id/AarSerieSeekBar"
android:layout_width="300dp"
android:layout_height="30dp"
android:max="50"
android:min="0"
android:progress="5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.306"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
<EditText
android:id="#+id/laanebelop"
android:layout_width="196dp"
android:layout_height="56dp"
android:autofillHints=""
android:ems="10"
android:hint="#string/hint"
android:inputType="numberDecimal"
android:textColorHint="#757575"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.641"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.248" />
<TextView
android:id="#+id/Laanebelop"
android:layout_width="103dp"
android:layout_height="40dp"
android:layout_marginTop="184dp"
android:text="#string/laaneBeløp"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.11"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/AarTall"
android:layout_width="35dp"
android:layout_height="30dp"
android:text="#string/_5"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.619"
app:layout_constraintStart_toEndOf="#+id/AarSerieSeekBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
<TextView
android:id="#+id/RenterTall"
android:layout_width="35dp"
android:layout_height="30dp"
android:text="#string/_5"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.633"
app:layout_constraintStart_toEndOf="#+id/RenterAnnSeekBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.383" />
<TextView
android:id="#+id/Rentenummer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/velg_rente"
app:layout_constraintBottom_toTopOf="#+id/RenterAnnSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.097"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Laanebelop"
app:layout_constraintVertical_bias="0.692" />
<TextView
android:id="#+id/antallAar"
android:layout_width="62dp"
android:layout_height="21dp"
android:text="#string/antall_aar"
app:layout_constraintBottom_toTopOf="#+id/AarSerieSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.097"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RenterAnnSeekBar"
app:layout_constraintVertical_bias="0.666" />
<Button
android:id="#+id/BeregnLaanAnnuitet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="264dp"
android:text="#string/bergen_l_net"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.757"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/AarSerieSeekBar"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/tilbakeTilVelkommen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="68dp"
android:text="#string/tilbake"
app:layout_constraintBottom_toTopOf="#+id/laanebelop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/textView2"
android:layout_width="180dp"
android:layout_height="40dp"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:text="#string/annuitet_l_n"
android:textStyle="bold"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/Laanebelop"
app:layout_constraintEnd_toStartOf="#+id/tilbakeTilVelkommen"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.066" />
</androidx.constraintlayout.widget.ConstraintLayout>

RecyclerView showing only 1st item, when tying to set dynamic height

I'm trying to set the dynamic height for my recycler view, because I have the Add button below it, that adds a new item to the list.
I'm using Constraint Layout in my parent fragment. I followed this advice, and when I add first item, it shows up and the ADD button slides down as expected, but the problem is that when I add the second one it just doesn't appear.
Here is the layout of my parent fragment:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".SecondFragment">
<Button
android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="444dp"
android:text="#string/cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/cancel_button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addItemActionButton" />
<Button
android:id="#+id/cancel_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="76dp"
android:text="#string/ok"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toRightOf="#id/cancel_button"
app:layout_constraintTop_toBottomOf="#+id/addItemActionButton"
app:layout_constraintVertical_bias="1.0" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="372dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toTopOf="#id/addItemActionButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.41"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.065" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/addItemActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="492dp"
android:clickable="true"
android:src="#android:drawable/ic_input_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/recyclerView"
tools:ignore="SpeakableTextPresentCheck" />
</androidx.constraintlayout.widget.ConstraintLayout>
And here's the one for the recycler item layout:
<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:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constrainedHeight="true">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
android:layout_width="288dp"
android:layout_height="51dp"
android:layout_marginBottom="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.024">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/item"
android:layout_width="300dp"
android:layout_height="71dp"
android:hint="#string/item" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here's my fragment code:
package com.example.progresstracker
import android.os.Bundle
import android.util.Log
import android.util.Log.INFO
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.progresstracker.databinding.FragmentSecondBinding
/**
* A simple [Fragment] subclass as the second destination in the navigation.
*/
class SecondFragment : Fragment() {
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<RecyclerAdapter.ViewHolder>? = null
private var _binding: FragmentSecondBinding? = null
private var items: ArrayList<String> = ArrayList()
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSecondBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.apply {
// set a LinearLayoutManager to handle Android
// RecyclerView behavior
layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
// set the custom adapter to the RecyclerView
adapter = RecyclerAdapter(items)
}
// linearLayoutManager = LinearLayoutManager(context)
// binding.recyclerView.layoutManager = linearLayoutManager
binding.cancelButton.setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
binding.addItemActionButton.setOnClickListener {
items.add("Testing..")
adapter = RecyclerAdapter(items)
adapter?.notifyItemInserted(items.size - 1)
binding.recyclerView.adapter = adapter
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
And the adapter:
package com.example.progresstracker
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class RecyclerAdapter(private val items: ArrayList<String>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var item: TextView
init {
item = itemView.findViewById(R.id.item)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recyclerview_item_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.item.text = items[position]
}
override fun getItemCount(): Int {
return items.size
}
}

Why it's unresolved reference error for calling setBackgroundResource() on an ' id ' in Mainactivity.kt?

package com.example.colormyviews
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setListeners()
}
private fun setListeners(){
val boxOneText = findViewById<TextView>(R.id.box_one_text)
val boxTwoText = findViewById<TextView>(R.id.box_two_text)
val boxThreeText = findViewById<TextView>(R.id.box_three_text)
val boxFourText = findViewById<TextView>(R.id.box_four_text)
val boxFiveText = findViewById<TextView>(R.id.box_five_text)
val rootConstraintLayout = findViewById<View>(R.id.info_text)
val redButton = findViewById<Button>(R.id.red_button)
val greenButton = findViewById<Button>(R.id.green_button)
val yellowButton = findViewById<Button>(R.id.yellow_button)
val clickableViews: List<View> =
listOf(
boxOneText, boxTwoText, boxThreeText,
boxFourText, boxFiveText, rootConstraintLayout,
redButton, greenButton, yellowButton
)
for (item in clickableViews){
item.setOnClickListener{makeColored(it)}
}
}
private fun makeColored(view: View){
when (view.id) {
// Boxes using Color class colors for the background
R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
R.id.box_two_text -> view.setBackgroundColor(Color.GRAY)
R.id.box_three_text -> view.setBackgroundColor(Color.BLUE)
R.id.box_four_text -> view.setBackgroundColor(Color.MAGENTA)
R.id.box_five_text -> view.setBackgroundColor(Color.BLUE)
R.id.red_button -> box_three_text.setBackgroundResource(R.color.my_red)
R.id.yellow_button -> box_four_text.setBackgroundResource(R.color.my_yellow)
R.id.green_button -> box_five_text.setBackgroundResource(R.color.my_green)
else -> view.setBackgroundColor(Color.LTGRAY)
}
}
}
XML code.
<?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/constraint_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/box_one_text"
style="#style/whiteBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="#dimen/margin_wide"
android:layout_marginRight="16dp"
android:text="#string/box_one"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/box_two_text"
style="#style/whiteBox"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/box_two"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/box_one_text" />
<TextView
android:id="#+id/box_three_text"
style="#style/whiteBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin_wide"
android:layout_marginEnd="#dimen/margin_wide"
android:text="#string/box_three"
app:layout_constraintBottom_toTopOf="#+id/box_four_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/box_two_text"
app:layout_constraintTop_toTopOf="#+id/box_two_text" />
<TextView
android:id="#+id/box_four_text"
style="#style/whiteBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin_wide"
android:layout_marginTop="#dimen/margin_wide"
android:layout_marginEnd="#dimen/margin_wide"
android:layout_marginBottom="#dimen/margin_wide"
android:text="#string/box_four"
app:layout_constraintBottom_toTopOf="#+id/box_five_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/box_two_text"
app:layout_constraintTop_toBottomOf="#+id/box_three_text" />
<TextView
android:id="#+id/box_five_text"
style="#style/whiteBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin_wide"
android:layout_marginEnd="#dimen/margin_wide"
android:text="#string/box_five"
app:layout_constraintBottom_toBottomOf="#+id/box_two_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/box_two_text"
app:layout_constraintTop_toBottomOf="#+id/box_four_text" />
<TextView
android:id="#+id/label_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:fontFamily="#font/roboto"
android:text="#string/how_to_play"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBaseline_toBaselineOf="#+id/info_text"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/info_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:fontFamily="#font/roboto"
android:text="#string/tap_the_boxes_and_buttons"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/label_text"
app:layout_constraintTop_toBottomOf="#+id/box_two_text"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/red_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="#string/button_red"
app:layout_constraintBaseline_toBaselineOf="#+id/yellow_button"
app:layout_constraintEnd_toStartOf="#+id/yellow_button"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/yellow_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="#string/button_yellow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/green_button"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/red_button"
app:layout_constraintTop_toBottomOf="#+id/info_text"
app:layout_constraintVertical_bias="1.0"/>
<Button
android:id="#+id/green_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:text="#string/button_green"
app:layout_constraintBaseline_toBaselineOf="#+id/yellow_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/yellow_button" />
</androidx.constraintlayout.widget.ConstraintLayout>
In makeColored() function, while calling setBackgroundResource() on box_three_text, box_four_text, box_five_text. It throws me an ' Unresolved reference error '. However id's with same name has been declared in XML file. I can't understand where the problem lies, Please help me to understand what's going on and why it is unable to read id's in Mainactivity.kt which has been declared in Mainactivity.xm.
instead of id use reference
R.id.red_button -> boxThreeText.setBackgroundResource(R.color.my_red)
R.id.yellow_button -> boxFourText.setBackgroundResource(R.color.my_yellow)
R.id.green_button -> boxFiveText.setBackgroundResource(R.color.my_green)
and make these buttons global variable. You can directly use ids if you are using kotlin synthetic, however I can't see any such import in your code. (And anyway you should not be using be kotlin synthetic as Kotlin-extension plugin is deprecated)
Instead of using id you have to define global variable, like this :
class MainActivity : AppCompatActivity() {
private lateinit var boxOneText: View
private lateinit var boxTwoText: View
private lateinit var boxThreeText: View
private lateinit var boxFourText: View
private lateinit var boxFiveText: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setListeners()
}
private fun makeColored(view: View) {
when (view.id) {
R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
R.id.box_two_text -> view.setBackgroundColor(Color.GRAY)
R.id.box_three_text -> view.setBackgroundColor(Color.BLUE)
R.id.box_four_text -> view.setBackgroundColor(Color.MAGENTA)
R.id.box_five_text -> view.setBackgroundColor(Color.BLUE)
R.id.red_button -> boxThreeText.setBackgroundResource(R.color.my_red)
R.id.yellow_button -> boxFourText.setBackgroundResource(R.color.my_yellow)
R.id.green_button -> boxFiveText.setBackgroundResource(R.color.my_green)
else -> view.setBackgroundColor(Color.LTGRAY)
}
}
private fun setListeners() {
boxOneText = findViewById<TextView>(R.id.box_one_text)
boxTwoText = findViewById<TextView>(R.id.box_two_text)
boxThreeText = findViewById<TextView>(R.id.box_three_text)
boxFourText = findViewById<TextView>(R.id.box_four_text)
boxFiveText = findViewById<TextView>(R.id.box_five_text)
val rootConstraintLayout = findViewById<View>(R.id.constraint_layout)
val redButton = findViewById<Button>(R.id.red_button)
val greenButton = findViewById<Button>(R.id.green_button)
val yellowButton = findViewById<Button>(R.id.yellow_button)
val clickableViews: List<View> =
listOf(
boxOneText, boxTwoText, boxThreeText,
boxFourText, boxFiveText, rootConstraintLayout,
redButton, greenButton, yellowButton
)
for (item in clickableViews) {
item.setOnClickListener { makeColored(it) }
}
}
}

LinearLayout Add multiple items

I faced a strange problem : I can't add more than one object dynamically on a LinearLayout , if they were already things , that works, So That can display multiple views
I tried with different views , there is only problems when i try to push one after the other
(there is two buttons in index 0 and 1 to test for multiple objects on the layout)
CODE :
val view = layoutInflater.inflate(R.layout.sensor_item, container, false)
val view2 = layoutInflater.inflate(R.layout.nosensor_item, container, false)
val insertPoint = viewOfLayout.findViewById(R.id.box_Parent) as LinearLayout
insertPoint.addView(view, 2)
//insertPoint.addView(view2, 3) //works
This Works too :
//insertPoint.addView(view, 3)
insertPoint.addView(view2, 2) //works
This doesn't works :
insertPoint.addView(view, 2)
insertPoint.addView(view2, 3) //doesn't works
Full Code (fragments.kt):
package com.corrupted.radheat.TEMPER
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import kotlinx.android.synthetic.main.sensor_item.view.*
class EditFragment : Fragment() {
lateinit var option : Spinner
lateinit var result : TextView
private lateinit var viewOfLayout: View
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewOfLayout = inflater.inflate(R.layout.edit_fragment, container, false)
//create a view to inflate the layout_item (the xml with the textView created before)
val view = layoutInflater.inflate(R.layout.sensor_item, container, false)
val view2 = layoutInflater.inflate(R.layout.nosensor_item, container, false)
val insertPoint = viewOfLayout.findViewById(R.id.box_Parent) as LinearLayout
insertPoint.addView(view, 2)
insertPoint.addView(view2, 3)
option = view.spinner as Spinner
result = view.textView7 as TextView
val options = arrayOf("A","V")
option.adapter = ArrayAdapter<String>(activity,android.R.layout.simple_list_item_1,options)
option.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
result.text = "0"
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
result.text = options[position]
}
}
return viewOfLayout
}
class InfoFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.info_fragment, container, false)
}
}
class ParamsFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.parameters_fragment, container, false)
}
}
Code of the fragment :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:id="#+id/box_Parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Code of the added view :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:fillViewport="true"
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="12dp"
android:background="#color/background_Item_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:text=".0 C°"
android:textColor="#color/Text_Color_Light"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/textView8"
app:layout_constraintStart_toEndOf="#+id/textView8"
app:layout_constraintTop_toTopOf="#+id/textView8"
app:layout_constraintVertical_bias="0.625" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_marginStart="4dp"
android:text=".0 C°"
android:textColor="#color/Text_Color_Light"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/textView5"
app:layout_constraintStart_toEndOf="#+id/textView5"
app:layout_constraintTop_toTopOf="#+id/textView5"
app:layout_constraintVertical_bias="0.79" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_marginStart="10dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="00"
android:textColor="#color/Text_Color_Light"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageButton"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.937" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:text="#string/ROOMtext"
android:textColor="#color/Text_Color_Light"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Spinner
android:id="#+id/spinner"
android:layout_width="45dp"
android:layout_height="43dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="8dp"
android:background="#color/UI_ITEM_OVERLAP_LIGHT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/imageButton"
android:layout_width="40dp"
android:layout_height="36dp"
android:layout_marginStart="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_keyboard_arrow_up_black_24dp" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="40dp"
android:layout_height="36dp"
android:layout_marginStart="8dp"
android:layout_marginTop="2dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="6dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageButton"
app:srcCompat="#drawable/ic_keyboard_arrow_down_black_24dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="00"
android:textColor="#color/Text_Color_Light"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.652" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
MainActivity.kt :
package com.corrupted.radheat.TEMPER
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.widget.*
class MainActivity : AppCompatActivity() {
private val fragmentManager = supportFragmentManager
private val fragmentTransaction = fragmentManager.beginTransaction()
private val editfragment = EditFragment()
private val infofragment = InfoFragment()
private val parametersfragment = ParamsFragment()
private fun showFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.action_edit -> {
showFragment(editfragment)
return#OnNavigationItemSelectedListener true
}
R.id.action_info-> {
showFragment(infofragment)
return#OnNavigationItemSelectedListener true
}
R.id.action_Settings-> {
showFragment(parametersfragment)
return#OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fragmentTransaction.add(R.id.fragment_container, infofragment)
fragmentTransaction.commit()
setContentView(R.layout.activity_main)
val navigation = findViewById<BottomNavigationView>(R.id.activity_main_bottom_navigation)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
// Create a GLSurfaceView instance and set it
// as the ContentView for this Activity.
}
}
Pic of it working : https://imgur.com/gallery/mLb4G5b
Thanks

Categories

Resources