Use right context - android

Need to paste context in my constructor in SwipeToDeleteCallback, which is located in the fragment:
private val swipeHandler = object : SwipeToDeleteCallback() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
presenter.removeListItem(viewHolder.adapterPosition)
}
}
Tried to insert requireContext() but catch KotlinNullPointerException.
Maybe I can somehow use the context here viewHolder.context?
Here is some code SwipeToDeleteCallback:
abstract class SwipeToDeleteCallback(context: Context) :
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
private val deleteIcon = context.getDrawableCompat(R.drawable.ic_log_out)
Also i called my fragment from MainActivity:
override fun onPostResume() {
super.onPostResume()
replaceFragment(TargetsFragment())
}
override fun showListOfTarget() {
replaceFragment(TargetsFragment())
}
Here is full code of my fragment:
class TargetsFragment : Fragment(), ListItemClickListener, SelectTargetViewContract, BaseDataSetContract {
private var recyclerView: RecyclerView? = null
private val presenter = TargetsPresenter(this)
private var adapter = TargetsAdapter(clickListener = this)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_target_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.setInitialData()
setupViews()
updateListData()
}
override fun onListItemClick(itemIndex: Int, itemCode: String) {
presenter.onListItemClick((adapter.getItem(itemIndex) as Target).guid)
}
override fun showTarget(guid: String) {
activity?.addFragment(TargetEditFragment.newInstance(guid))
}
override fun dataSetChanged() {
updateListData()
adapter.notifyDataSetChanged()
}
override fun updateViewContent() {
adapter.data = presenter.targetList
recyclerView?.adapter = adapter
recyclerView?.setVisible(presenter.shouldShowContent())
emptyView?.setVisible(presenter.shouldShowEmptyView())
}
private fun updateListData() {
if (presenter.firebaseUser == null) {
Log.d("some", "loadLogInView")
} else {
presenter.getTargetsFromDb()
}
}
private val swipeHandler = object : SwipeToDeleteCallback() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
presenter.removeListItem(viewHolder.adapterPosition)
}
}
private fun setupViews() {
recyclerView = view?.findViewById(R.id.recyclerView)
recyclerView?.layoutManager = LinearLayoutManager(activity)
ItemTouchHelper(swipeHandler).attachToRecyclerView(recyclerView)
}
}

You can use
yourViewHolder.itemView.context
to get the context of yourViewHolder
After clarification from OP:
Initially I thought you only wanted to get context from your ViewHolder, but here's an addition to my answer:
Try moving your code which requires context to onAttach, which you will have to override, from the documentation : https://developer.android.com/guide/components/fragments.html
Caution: If you need a Context object within your Fragment, you can call getContext(). However, be careful to call getContext() only when the fragment is attached to an activity. When the fragment isn't attached yet, or was detached during the end of its lifecycle, getContext() returns null.
The method you're looking for looks like this :
override fun onAttach(context: Context) {
super.onAttach(context)
}
You will probably be safe to move all your code which requires context inside this method and assign it as you need to

Related

My recyclerview resets when I add or delete an item from a Table (with Room) in Kotlin

First of all, I am Spanish so my english is not good.
I have an app with Kotlin and room, and it has a Recyclerview.
I have 3 tables: coaster, user and favorite.
The user can add coasters to favorite, and this is done succesfully.
The problem that I have is that when the user clicks on the button to add or delete from favorites, the recyclerview resets, it displays again. So it scrolls to the top of the Screen, and also some odd spaces appears after the element.
I also have a function to search, and it happens the same: spaces appears after each element when I am searching.
I have tried everything: notifyItemChanged,
notifyDataSetChanged... it doesnt work! I also tried removing the observer once from the recyclerview...
My main activity:
class CoasterFragment : Fragment() {
lateinit var coasterListener: CoasterListener
lateinit var usuarioCoaster: List\<UsuarioCoaster\>
private lateinit var searchView: SearchView
private lateinit var cAdapter: CoasterRecyclerViewAdapter
private var \_binding: FragmentCoasterBinding? = null
private val binding get() = \_binding!!
private val viewModel: CoastersViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentCoasterBinding.inflate(inflater, container, false)
val root: View = binding.root
/* val livedata = viewModel.coasters()
livedata.observe(viewLifecycleOwner,object: Observer <List<CoasterFavorito>> {
override fun onChanged(it: List<CoasterFavorito>) {
createRecyclerView(it)
livedata.removeObserver(this)
}
})*/
viewModel.coasters().observe(viewLifecycleOwner){createRecyclerView(it)}
coasterListener = CoasterListenerImpl(requireContext(), viewModel)
searchView = binding.search
searchView.clearFocus()
searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
if(query != null){
searchDatabase(query)
}
return true
}
override fun onQueryTextChange(query: String?): Boolean {
if(query != null){
searchDatabase(query)
}
return true
}
})
return root
}
fun createRecyclerView(coasters: List<CoasterFavorito>) {
cAdapter =
CoasterRecyclerViewAdapter(
coasters as MutableList<CoasterFavorito>,
coasterListener,
requireContext()
)
val recyclerView = binding.recyclerCoaster
recyclerView.apply {
layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
adapter = cAdapter
addItemDecoration(DividerItemDecoration(context, RecyclerView.VERTICAL))
cAdapter.notifyDataSetChanged()
}
}
fun searchDatabase(query: String) {
val searchQuery = "%$query%"
viewModel.searchDatabase(searchQuery).observe(viewLifecycleOwner) { createRecyclerView(it)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
my adapter:
class CoasterRecyclerViewAdapter(val coasters: List<CoasterFavorito>, val listener: CoasterListener,
val context: Context, ) : RecyclerView.Adapter<CoasterRecyclerViewAdapter.ViewHolder>(){
class ViewHolder private constructor(val binding: CoasterItemBinding, private val listener: CoasterListener,
private val context: Context): RecyclerView.ViewHolder(binding.root){
fun relleno(data: CoasterFavorito){
binding.nombre.text = data.coaster.nombre
binding.parque.text = data.coaster.parque
binding.ciudad.text = data.coaster.ciudad
binding.provincia.text = data.coaster.provincia
binding.comunidad.text = data.coaster.comunidadAutonoma
Glide
.with(context)
.load(data.coaster.imagen)
.centerCrop()
.into(binding.imagen)
binding.check.isChecked = data.favorito
binding.check.setOnClickListener{
if (data.favorito) {
listener.delFavorito(data.coaster.id)
binding.check.isChecked = false
} else {
listener.addFavorito(data.coaster.id)
binding.check.isChecked = true
}
}
}
companion object{
fun crearViewHolder(parent: ViewGroup, listener: CoasterListener, adapter: CoasterRecyclerViewAdapter, context: Context):ViewHolder{
val layoutInflater = LayoutInflater.from(parent.context)
val binding = CoasterItemBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding, listener, context )
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.crearViewHolder(parent, listener, this, context)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.relleno(coasters[position])
override fun getItemCount() = coasters.size
}
interface CoasterListener {
fun addFavorito(id: Long)
fun delFavorito(id: Long)
}
I have tried everything: notifyItemChanged,
notifyDataSetChanged... it doesnt work! I also tried removing the observer once from the recyclerview...
Your createRecyclerView function should be invoked only once in a whole lifecycle of the Fragment. You should not create any new RecyclerView.Adapter, or set a LayoutManager to the RecyclerView every time your data set changes.
Therefore the Observer used in viewModel.coasters.observe() should only submit a new List to the existing Adapter and call .notifyDataSetChanged(), or other notifying functions.

Android Adapter redrawing view with all the same original items rather than removing selected item

I've been trying to delete an item from my list so that it updates without the removed item, but the list seems to redraw itself and keeps displaying all the original items as before. For a short bit of time it's possible to see the item as if it's being removed, however, due to this redrawing everything gets back to what it was before the removal.
I've tried several combinations of the following methods but none of them seem to work in this case.
adapter.notifyItemRangeChanged(position, adapter.itemCount)
adapter.notifyItemRemoved(position)
adapter.notifyItemChanged(position)
adapter.notifyDataSetChanged()
These are my files. Please notice I'm using the Groupie library as a replacement for the default RecyclerView.
class RecyclerProductItem(
private val activity: MainActivity,
private val product: Product,
private val onItemClickListener: OnItemClickListener?
) : Item<GroupieViewHolder>() {
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.apply {
with(viewHolder.itemView) {
ivTrash.setOnClickListener {
if (onItemClickListener != null) {
Toast.makeText(context, "delete method to be added here", Toast.LENGTH_SHORT).show()
onItemClickListener.onClick(viewHolder.adapterPosition)
// deleteProduct(product.id)
}
}
}
}
}
interface OnItemClickListener {
fun onClick(position: Int) //pass your object types.
}
override fun getLayout() = R.layout.recyclerview_item_row
}
And here my fragment:
class ProductsListFragment : Fragment() {
private lateinit var adapter: GroupAdapter<GroupieViewHolder>
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_products_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val linearLayoutManager = LinearLayoutManager(activity)
recyclerView.layoutManager = linearLayoutManager
adapter = GroupAdapter()
recyclerView.adapter = adapter
loadProducts()
}
/**
* API calls
*/
private fun loadProducts() {
GetProductsAPI.postData(object : GetProductsAPI.ThisCallback,
RecyclerProductItem.OnItemClickListener {
override fun onSuccess(productList: List<JsonObject>) {
Log.i(LOG_TAG, "successful network call")
for (jo in productList) {
val gson = GsonBuilder().setPrettyPrinting().create()
val product: Product =
gson.fromJson(jo, Product::class.java)
adapter.add(
RecyclerProductItem(
activity as MainActivity,
Product(
product.id,
product.title,
product.description,
product.price
), this
)
)
}
}
override fun onClick(position: Int) {
Log.i(LOG_TAG, position.toString())
adapter.notifyItemRangeChanged(position,
adapter.itemCount)
adapter.notifyItemRemoved(position)
}
})
}
}
Many thanks.
Simple sample
class GroupAdapter(private val items: MutableList<Any>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
fun removeByPosition(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}

callback from fragment in ViewPager2 adapter

Ok, I got the following fragment with callback there witch I'm setting to ViewPager2 adapter:
class PremiumFragment : BaseFragment(), OnPageChanged {
override fun getLogTag(): String {
return TAG
}
private lateinit var pagerCounter: ImageView
private lateinit var viewPager: ViewPager2
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewPager = view.findViewById(R.id.view_pager) as ViewPager2
viewPager.adapter = ViewPagerAdapter(this)
pagerCounter = view.findViewById(R.id.counter)
}
companion object {
const val TAG = "PremiumFragment"
fun getInstance(): BaseFragment {
Log.d(TAG, "getInstance()")
val args = Bundle()
args.putInt(ARG_LAYOUT_ID, R.layout.premium_f)
val fragment =
PremiumFragment()
fragment.arguments = args
return fragment
}
}
override fun onPageChanged() {
when (viewPager.currentItem) {
0 -> pagerCounter.setImageResource(R.drawable.circle_1)
1 -> pagerCounter.setImageResource(R.drawable.circle_2)
2 -> pagerCounter.setImageResource(R.drawable.circle_3)
}
}
}
My adapter:
class ViewPagerAdapter constructor(val callback: OnPageChanged) : RecyclerView.Adapter<PagerVH>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PagerVH =
PagerVH(LayoutInflater.from(parent.context).inflate(R.layout.viewpager_f, parent, false))
override fun getItemCount(): Int = Images.values().size
override fun onBindViewHolder(holder: PagerVH, position: Int) = holder.itemView.run {
pager_container.findViewById<ImageView>(R.id.imageView)
.setImageResource(Images.values()[position].image)
}
override fun getItemViewType(position: Int): Int {
callback.onPageChanged()
return super.getItemViewType(position)
}
companion object {
enum class Images(private val value: Int, val image: Int) {
First(0, R.drawable.wow_girl),
Second(1, R.drawable.insights_girl_2),
Third(2, R.drawable.remind_girl);
}
}
}
It should set new drawable every time we swipe ViewPager, but it changes image in fragment only once an then it is not working, have completely no idea where in adapter I should call my callback for a proper behavior, please tell me where should I call this callback? Appreciate any advices!
So I found out that you should call callback from onViewDetachedFromWindow for it calls every time you swipe fragment, and it is quite logical
override fun onViewDetachedFromWindow(holder: PagerVH) {
callback.onPageChanged()
super.onViewDetachedFromWindow(holder)
}

Implementing ListAdapter for a RecyclerView Fragment

I've done this successfully with a normal ViewAdapter but I can't seem to get it working with a ListAdapter.
Here is my Fragment that does most of the work:
class CrimeListFragment: Fragment() {
//Required interface for hosting activities
interface Callbacks {
fun onCrimeSelected(crimeId: UUID)
}
private var callbacks: Callbacks? = null
private lateinit var crimeRecyclerView: RecyclerView
private val crimeListViewModel: CrimeListViewModel by lazy {
ViewModelProviders.of(this).get(CrimeListViewModel::class.java)
}
override fun onAttach(context: Context) {
super.onAttach(context)
callbacks = context as Callbacks?
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_crime_list, container, false)
crimeRecyclerView =
view.findViewById(R.id.crime_recycler_view) as RecyclerView
crimeRecyclerView.layoutManager = LinearLayoutManager(context)
crimeRecyclerView.adapter = CrimeListAdapter(emptyList())
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
crimeListViewModel.crimeListLiveData.observe(
viewLifecycleOwner,
Observer { crimes ->
crimes?.let {
Log.i(TAG, "Got crimes ${crimes.size}")
updateUI(crimes)
}
}
)
}
override fun onDetach() {
super.onDetach()
callbacks = null
}
private fun updateUI(crimes: List<Crime>) {
crimeRecyclerView.adapter = CrimeListAdapter(crimes)
}
companion object {
fun newInstance(): CrimeListFragment {
return CrimeListFragment()
}
}
private inner class CrimeHolder(view: View)
: RecyclerView.ViewHolder(view), View.OnClickListener {
private lateinit var crime: Crime
private val titleTextView = itemView.findViewById<TextView>(R.id.crime_title)
private val dateTextView = itemView.findViewById<TextView>(R.id.crime_date)
private val solvedImageView = itemView.findViewById<ImageView>(R.id.crime_solved)
init {
itemView.setOnClickListener(this)
}
fun bind(crime: Crime) {
this.crime = crime
titleTextView.text = crime.title
dateTextView.text = crime.date.toString()
solvedImageView.visibility = if(crime.isSolved) {
View.VISIBLE
} else {
View.GONE
}
}
override fun onClick(v: View) {
callbacks?.onCrimeSelected(crime.id)
}
}
private inner class CrimeListAdapter(var crimes: List<Crime>)
: ListAdapter<Crime, CrimeHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CrimeHolder {
val view =
layoutInflater.inflate(R.layout.list_item_crime, parent, false)
return CrimeHolder(view)
}
override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
holder.bind(crimes[position])
}
}
private inner class DiffCallback: DiffUtil.ItemCallback<Crime>() {
override fun areItemsTheSame(oldItem: Crime, newItem: Crime): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Crime, newItem: Crime): Boolean {
return oldItem == newItem
}
}
}
And here is the fragment's viewmodel:
class CrimeListViewModel: ViewModel() {
private val crimeRepository = CrimeRepository.get()
val crimeListLiveData = crimeRepository.getCrimes() //returns LiveData<List<Crime>>
}
Android documentation has this regarding ListAdapter:
While using a LiveData is an easy way to provide data to the adapter, it isn't required - you can use submitList(List) when new lists are available.
I'm supposed to submit a new list instead of creating a new ListAdapter object each time I update the UI. But crimeRecyclerView.adapter has no .submitList() function. So how do I pass on the new list?
LiveData is still new to me so I'm not quite clear on this. I already observe a LiveData stored in my viewmodel. So what do I observe this time? Or do I just add code to my existing Observer?
Finally when I run the code in this state, phone shows an empty RecyclerView. Only UpdateUI() gets called, none of CrimeListAdapter's functions get called. I'm not sure if this is a real problem or just the consequence of the above.
1.I'm supposed to submit a new list instead of creating a new ListAdapter object each time I update the UI. But
crimeRecyclerView.adapter has no .submitList() function. So how do I
pass on the new list?
crimeRecyclerView.adapter return RecyclerView.Adapter type
submitList() is a method of ListAdapter, a sub-class of RecyclerView.Adapter
You need to cast from super to sub class before calling that method, like this.
(crimeRecyclerView.adapter as CrimeListAdapter).submitList(crimes)
2.LiveData is still new to me so I'm not quite clear on this. I already observe a LiveData stored in my viewmodel. So what do I
observe this time? Or do I just add code to my existing Observer?
Your code for this part is good, no need to do more.
3.Finally when I run the code in this state, phone shows an empty RecyclerView. Only UpdateUI() gets called, none of CrimeListAdapter's
functions get called. I'm not sure if this is a real problem or just
the consequence of the above.
The best part of using ListAdapter is you do not need to provide a list of data (crimes in your case) to constructor.
Back to your code, you need to change 3 things.
// crimeRecyclerView.adapter = CrimeListAdapter(emptyList())
crimeRecyclerView.adapter = CrimeListAdapter()
and
// crimeRecyclerView.adapter = CrimeListAdapter(crimes)
(crimeRecyclerView.adapter as CrimeListAdapter).submitList(crimes)
and
//private inner class CrimeListAdapter(var crimes: List<Crime>) :
// ListAdapter<Crime, CrimeHolder>(DiffCallback()) {
//
// override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CrimeHolder {
// val view = layoutInflater.inflate(R.layout.list_item_crime, parent, false)
// return CrimeHolder(view)
// }
//
// override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
// holder.bind(crimes[position])
// }
//}
private inner class CrimeListAdapter : ListAdapter<Crime, CrimeHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CrimeHolder {
val view = layoutInflater.inflate(R.layout.list_item_crime, parent, false)
return CrimeHolder(view)
}
override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
holder.bind(getItem(position))
}
}

Kotlin RecycleView does not work correctly

I want to create a small application that once the user clicks on floating button action to add element. It will be added automatically
to the top of the recycle view.
I have created for this A main activity which contains the fragment of the recycler and the add flotten.
Once the user clicks on this button a fragmented dialog is shown to insert the element. Once the user confirms i want to add the new element to the top of the recycle view.
TO did I used a global array which contains the item.
I have not implemented the logic yet for that. But what surprised me once I click on confirm button of the shown dialog the element added correctly to the global array, however, the recycle view on his own without any action on it duplicate the latest element.
I used the model view presenter for that and here are my diff classes
1.MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addFragment(InterFragment(), R.id.container)
fab.setOnClickListener { view ->
val dialog = IntervAddFragment()
val ft = supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
}
}
2.ADDFragmet
class IntervAddFragment : DialogFragment(), AddContract.View
{
val presenter: AddPresenter by lazy { AddPresenter(this) }
var dat=""
var plom=""
var typ=""
override fun onCreate(savedInstanceState: Bundle?) { ....}
override fun onStart() {.... }
override fun onCreateView(inflater: LayoutInflater?, parent: ViewGroup?, state: Bundle?): View? {...}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {....}
fun on_confirmClick()
{
presenter.on_confirmClick(dat,plom,typ)
Log.e("errrr",presenter.getList().toString())
dismiss()
}
fun fillSpinerPlom(view : View?) {.... }
fun fillSpinerType(view : View?) {.... }
private fun updateDateInView(datep:String) {....}
}
3.IntervFragement
InterFragment: Fragment(), InterContract.View {
var views: View? = null
var List_inter_adapter: InterListAdapter? = null
private var recyclerView: RecyclerView? = null
val presenter: InterventionPresenter by lazy { InterventionPresenter(this) }
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {.... }
interface ClickListener {
fun onClick(view: View, position: Int)
fun onLongClick(view: View?, position: Int)
}
internal class RecyclerTouchListener(context: Context, recyclerView: RecyclerView, private val clickListener: ClickListener?) : RecyclerView.OnItemTouchListener {..... }
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {.....}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = views!!.findViewById<View>(R.id.interv_item_listview) as RecyclerView
List_inter_adapter = InterListAdapter(activity, presenter.getList(true))
recyclerView!!.adapter = List_inter_adapter
recyclerView!!.layoutManager = LinearLayoutManager(activity)
}
}
4.InterPresenter
class InterventionPresenter(val view: InterContract.View)
{
fun getList(firstTime:Boolean): LinkedList<InterItem> {
if(firstTime)
return populateList().list
else
return items
}
fun populateList(): ListInter
{
val item1 = InterItem(1, DateT(2018, Calendar.FEBRUARY, 6).date, plomb.get(0), types.get(0))
val item2 = InterItem(2, DateT(2018, Calendar.MARCH, 8).date, plomb.get(1), types.get(1))
val item3= InterItem(3, DateT(2018, Calendar.MAY, 10).date, plomb.get(2), types.get(2))
val lstint = ListInter()
lstint.list= LinkedList(listOf(item1, item2, item3))
items=lstint.list
return lstint
}
companion object {
val plomb= LinkedList<String>(listOf("Dina", "Lili", "Wiseem"))
val types= LinkedList<String>(listOf("type1","type2","type3"))
lateinit var items: LinkedList<InterItem>
}
}
5.ADD Presenter
class AddPresenter(val view: AddContract.View)
{
fun on_confirmClick(date:String,plom:String,type:String)
{
val item= InterItem(items.size+1,date,plom,type)
items.push(item)
}
fun getList(): LinkedList<InterItem> {
return items
}
fun getplom(): LinkedList<String>
{ return plomb
}
fun getType(): LinkedList<String>
{ return types
}
}
6.InterListAdapter
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem>) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
internal var linkedList = LinkedList<InterItem>()
private val inflater: LayoutInflater
//private lateinit var listener: OnTaskSelected
init {... }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {... }
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.numero?.text=(linkedList[position].numero).toString()
holder.date?.text=linkedList[position].date
holder.plom?.text=linkedList[position].plom
holder.type?.text=linkedList[position].type
}
override fun getItemCount(): Int {
return linkedList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var numero: TextView?=null
var date: TextView?=null
var plom: TextView?=null
var type: TextView?=null
var btn_delete: Button?=null
var btn_update: Button?=null
init {
numero = itemView.findViewById(R.id.numero)
date = itemView.findViewById(R.id.date)
plom = itemView.findViewById(R.id.plom)
type = itemView.findViewById(R.id.type)
btn_delete = itemView.findViewById(R.id.btn_supprimer)
btn_update = itemView.findViewById(R.id.btn_modifier)
}
}
}
and here is the ListInter
class ListInter
{
var list= LinkedList<InterItem>()
get() = field
set(value){field = value}
}
RecyclerView can't handle array change event by itself. So, you should notify it by calling the following after you've added element to array:
recyclerView.getAdapter().notifyItemInserted(items.size() - 1)

Categories

Resources