I show a list of items using adapter and recyclerview. Each item shows only 4 lines of biography-textView. In order to see whole biography, user clicks 'expand' textView. My code functions but there is a problem because sometimes (somehow randomly) one 'expand' click (f.e. in item No 1) causes expanding 2-3 biography textView more in another items(f.e. items No 7 and 12). What is wrong with my code? How to check it/identify why items textView are extra expand?
Can anyone help?
class ShowMastersAdapter (
private val masterList: ArrayList<Master>,
private val itemListener: OnItemClickListener
) : RecyclerView.Adapter<ShowMastersAdapter.ShowMasterViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShowMasterViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_master, parent, false)
return ShowMasterViewHolder(view)
}
override fun onBindViewHolder(holder: ShowMasterViewHolder, position: Int) {
holder.bindData(position)
}
override fun getItemCount(): Int {
return masterList.size
}
inner class ShowMasterViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindData(position: Int) {
val masterBiography = itemView.findViewById<TextView>(R.id.item_master_biography)
val masterExpandBiography =itemView.findViewById<TextView>(R.id.item_master_expand_text)
masterBiography.text = masterList[position].biography
masterExpandBiography.setOnClickListener {
itemListener.onReadMoreTextClick(masterExpandBiography, masterBiography)
}
}
}
interface OnItemClickListener {
fun onReadMoreTextClick(expandText: TextView, biographyText: TextView)
}
}
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/layout_top_part">
<TextView
android:id="#+id/item_master_biography"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/item_master_margin_start"
android:layout_marginEnd="#dimen/item_master_margin_end"
android:ellipsize="end"
android:maxLines="4"
android:text="unknown"
android:textSize="#dimen/font_main_size_item_master"
app:layout_constraintBottom_toTopOf="#+id/item_master_expand_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/item_master_biography_label" />
<TextView
android:id="#+id/item_master_expand_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:text="#string/it_master_expand_text"
android:textColor="#color/text_as_link"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class FragmentShowMasters() : Fragment(), ShowMastersAdapter.OnItemClickListener{
private var listOfMasters: ArrayList<Master> = ArrayList()
private lateinit var myRecycler: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState:Bundle?): View {
myView = inflater.inflate(R.layout.fragment_show_masters, container, false)
myRecycler = myView.findViewById(R.id.recycler_show_masters)
myRecycler.setHasFixedSize(true)
myRecycler.adapter = ShowMastersAdapter(listOfMasters, this, highlightSearchText)
myRecycler.adapter?.notifyDataSetChanged()
myRecycler.layoutManager = LinearLayoutManager(this.context)
return myView
}
override fun onReadMoreTextClick(expandText: TextView, biographyText: TextView) {
if (biographyText.maxLines == 4) {
biographyText.maxLines = Int.MAX_VALUE
expandText.text = getString(R.string.it_master_shrink_text)
} else {
biographyText.maxLines = 4
expandText.text = getString(R.string.it_master_expand_text)
}
}
}
Related
enter image description here
When I click on cardview I want the other cardview color to turn white
here design is that i show in recyclerview
<?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="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:backgroundTint="#android:color/transparent"
android:elevation="0dp"
android:paddingBottom="10dp">
<androidx.cardview.widget.CardView
android:id="#+id/mainCard"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_marginLeft="1dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="15dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/cardImage"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
app:srcCompat="#drawable/cate1" />
<TextView
android:id="#+id/mainText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="10dp"
android:text="Telefon, Tablet\nve Aksesuarlar"
android:textColor="#302E2E"
android:textSize="10sp" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="#+id/colorCard"
android:layout_width="82dp"
android:layout_height="102dp"
android:visibility="invisible"
app:cardBackgroundColor="#color/orange"
app:cardCornerRadius="10dp"
app:cardElevation="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
The block with adapter codes for the recyclerview that I have listed
I couldn't understand the logic in setOnclickListener
and
I don't know how to make an algorithm
class CategoryMainAdapter(val mContext: Context) :
RecyclerView.Adapter<CategoryMainAdapter.ViewHolderClass>() {
var categoryMainList: List<CategoryMain> = listOf()
inner class ViewHolderClass(view: View) : RecyclerView.ViewHolder(view) {
val mainCard: CardView
val cardImage: ImageView
val mainText: TextView
val colorCard: CardView
init {
mainCard = view.findViewById(R.id.mainCard)
cardImage = view.findViewById(R.id.cardImage)
mainText = view.findViewById(R.id.mainText)
colorCard = view.findViewById(R.id.colorCard)
}
}
#SuppressLint("NotifyDataSetChanged")
fun setList(list: List<CategoryMain>) {
categoryMainList = list
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderClass {
val design =
LayoutInflater.from(mContext).inflate(R.layout.main_category_design, parent, false)
return ViewHolderClass(design)
}
override fun onBindViewHolder(holder: ViewHolderClass, position: Int) {
val categoryMain = categoryMainList[position]
holder.mainText.text = categoryMain.categoryName
holder.cardImage.setImageResource(categoryMain.categoryPhoto)
holder.mainCard.setOnClickListener() {
holder.colorCard.visibility = View.VISIBLE
holder.mainText.setTextColor(ContextCompat.getColor(mContext, R.color.orange))
}
}
override fun getItemCount(): Int {
return categoryMainList.size
}
}
You can use a multi-select functionality in recycler view like this: How to implement multi-select in RecyclerView? or Multiple selected items RecyclerView in Activity.java
i solved my problem
now when i click on which cardview its color changes
class CategoryMainAdapter(val mContext: Context) :
RecyclerView.Adapter<CategoryMainAdapter.ViewHolderClass>() {
var categoryMainList: List<CategoryMain> = listOf()
var clikedPosition : Int = -1
inner class ViewHolderClass(view: View) : RecyclerView.ViewHolder(view) {
val mainCard: CardView
val cardImage: ImageView
val mainText: TextView
val colorCard: CardView
init {
mainCard = view.findViewById(R.id.mainCard)
cardImage = view.findViewById(R.id.cardImage)
mainText = view.findViewById(R.id.mainText)
colorCard = view.findViewById(R.id.colorCard)
}
}
#SuppressLint("NotifyDataSetChanged")
fun setList(list: List<CategoryMain>) {
categoryMainList = list
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderClass {
val design =
LayoutInflater.from(mContext).inflate(R.layout.main_category_design, parent, false)
return ViewHolderClass(design)
}
override fun onBindViewHolder(holder: ViewHolderClass, position: Int) {
val categoryMain = categoryMainList[position]
holder.mainText.text = categoryMain.categoryName
holder.cardImage.setImageResource(categoryMain.categoryPhoto)
if (categoryMain.isSelected == true){
categoryMainList[position].isSelected = false
holder.colorCard.visibility = View.INVISIBLE
holder.mainText.setTextColor(ContextCompat.getColor(mContext, R.color.blacklow))
}
holder.mainCard.setOnClickListener() {
if (clikedPosition != -1){
notifyItemChanged(clikedPosition)
}
clikedPosition = position
categoryMainList[position].isSelected = true
holder.colorCard.visibility = View.VISIBLE
holder.mainText.setTextColor(ContextCompat.getColor(mContext, R.color.orange))
}
}
override fun getItemCount(): Int {
return categoryMainList.size
}
}
I am new to mobile development with kotlin and I am trying to add a new item to the recyclerview.
The item is added to the recycler view but the text is not visible. I don't get what it's wrong.
I am using Kotlin in Android Studio 4.2
The class AgentAttributes only contains two properties:val Name:String ,val Value:String
**activity_main.xml**
<EditText
android:id="#+id/etSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="No emp"
app:layout_constraintEnd_toStartOf="#+id/btnSearch"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#android:string/search_go"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvAgentAttributes"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etSearch" />
**MainActivity.kt**
private lateinit var agentAttributesAdapter:AgentAttributesAdapter
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//setContentView(R.layout.activity_main)
//constructor
agentAttributesAdapter = AgentAttributesAdapter(mutableListOf())
//Definition of Recycler view adapter
binding.rvAgentAttributes.adapter = agentAttributesAdapter
binding.rvAgentAttributes.layoutManager = LinearLayoutManager(this)
//THIS IS THE WAY THAT I AM TRYING TO ADD A NEW ITEM
val agentAttr = AgentAttributes("Nombre","JOEL ROMUALDO LOPEZ SALIDO")
agentAttributesAdapter.addAttributes(agentAttr)
**AgentAttributesAdapter**
class AgentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AgentViewHolder {
return AgentViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.agent_details,
parent,
false
)
)
override fun onBindViewHolder(holder: AgentViewHolder, position: Int) {
val layoutInflater = LayoutInflater.from(holder.itemView.context)
binding = AgentDetailsBinding.inflate(layoutInflater)
//val view = binding.root
val currentAgent = agent_attributes[position]
holder.itemView.apply {
binding.tvAttribute.text = currentAgent.Name.toString()
}
}
override fun getItemCount(): Int {
return agent_attributes.size
}
fun addAttributes(attr:AgentAttributes){
agent_attributes.add(attr)
notifyItemInserted(agent_attributes.size - 1)
}
There's no need to inflate your layout in the "binding" step:
override fun onBindViewHolder(viewHolder: ChoicesViewHolder, pos: Int) {
AgentDetailsBinding.bind(viewHolder.itemView).apply {
val currentAgent = agent_attributes[position]
tvAttribute.text = currentAgent.Name.toString()
}
}
PS: variables should be lower case, so currentAgent should have a name, no Name
I'm using MVVC pattern and I'm populating a recyclerView with data from database using Room. At the Logcat, data return correctly and is looped correctly, but recyclerview display seven elements and in the eighth starts to overwrite it with the nineth and tenth elements e after that create 2 more elements with the first 2 elements from list.
I'm coudn't find what is wrong with my code.
So, I'm asking for some help.
AvaliacaoFragment.kt:
class AvaliacaoFragment : Fragment() {
private lateinit var ctx: Context
private var _binding: FragmentAvaliacaoBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
private lateinit var textoSemSecoes: TextView
private lateinit var nomeAvaliacao: TextView
private lateinit var dataAvaliacao: TextView
private val args by navArgs<AvaliacaoFragmentArgs>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentAvaliacaoBinding.inflate(inflater, container, false)
return binding.root
// return inflater.inflate(R.layout.fragment_avaliacoes, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ctx = view.context
// dialogNovaAvaliacao = MaterialAlertDialogBuilder(ctx, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen)
// dialogNovaAvaliacao = MaterialAlertDialogBuilder(ctx,R.style.AlertDialogTheme)
// val builder = MaterialDatePicker.Builder.datePicker()
textoSemSecoes = view.findViewById(R.id.texto_sem_secoes)
nomeAvaliacao = view.findViewById(R.id.nome_avaliacao)
dataAvaliacao = view.findViewById(R.id.data_avaliacao)
nomeAvaliacao.text = args.currentAvaliacao.nome
dataAvaliacao.text = args.currentAvaliacao.dataCriacao
/*
btnAddAvaliacao = view.findViewById(R.id.btn_add_avaliacao)
btnAddAvaliacao.setOnClickListener {
findNavController().navigate(R.id.action_navigation_avaliacoes_to_addAvaliacaoFragment)
}
*/
// Recycler
val recyclerAdapter = SecaoAdapter()
val recyclerView = binding.secaoRecyclerView
recyclerView.adapter = recyclerAdapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
// ViewModelFactory para passar argumentos para a ViewModel
val factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return SecaoViewModel(Application(), args.currentAvaliacao.id) as T
}
}
// ViewModel
mSecaoViewModel = ViewModelProvider(this, factory).get(SecaoViewModel::class.java)
mSecaoViewModel.readAllData.observe(viewLifecycleOwner, Observer { secaoList ->
if(secaoList.isNotEmpty()){
Log.d(TAG, "secaoList: ${secaoList.toString()}")
Log.d(TAG, "secaoList.size: ${secaoList.size}")
textoSemSecoes.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
recyclerAdapter.setData(secaoList.sortedBy { it.codigo.toInt() })
} else {
textoSemSecoes.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
}
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private val TAG: String = AvaliacaoFragment::class.java.name
lateinit var mSecaoViewModel: SecaoViewModel
private lateinit var btnAddSecao: FloatingActionButton
private lateinit var dialogNovaSecao: MaterialAlertDialogBuilder
}
}
SecaoAdapter.kt:
class SecaoAdapter: RecyclerView.Adapter<SecaoAdapter.SecaoViewHolder>() {
private val TAG: String = SecaoAdapter::class.java.name
private var secaoList = emptyList<Secao>()
private lateinit var binding: ItemSecaoBinding
class SecaoViewHolder(itemBinding: ItemSecaoBinding): RecyclerView.ViewHolder(itemBinding.root) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SecaoViewHolder {
binding = ItemSecaoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return SecaoViewHolder(binding)
}
override fun getItemCount(): Int {
return secaoList.size
}
override fun onBindViewHolder(holder: SecaoViewHolder, position: Int) {
Log.d(TAG, "position: $position")
val currentItem = secaoList[position]
Log.d(TAG, "currentItem: ${currentItem.toString()}")
binding.secaoCodigo.text = currentItem.codigo
binding.secaoNome.text = currentItem.nome
binding.secaoMediaTotal.text = currentItem.mediaPositivo.toString()
binding.secaoPerguntasNaoAplicaveis.text = currentItem.qdePerguntasNaoAplicaveis.toString()
binding.secaoPerguntasRespondidas.text = currentItem.qdePerguntasRespondidas.toString()
binding.secaoPerguntasTotais.text = currentItem.qdePerguntas.toString()
binding.cardSecao.setOnClickListener {
val action = AvaliacaoFragmentDirections.actionAvaliacaoFragmentToSecaoFragment(currentItem)
holder.itemView.findNavController().navigate(action)
}
}
fun setData(secao: List<Secao>){
this.secaoList = secao
notifyDataSetChanged()
}
}
fragment_avaliacao.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"
android:background="#color/colorPrimaryDark"
tools:context=".ui.secoes.AvaliacaoFragment">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container_titulo_avaliacao"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
>
<TextView
android:id="#+id/nome_avaliacao"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/padrao_avaliacao_sem_nome"
android:textSize="24sp"
android:textColor="#color/colorIcons"
android:textAlignment="center"
/>
<TextView
android:id="#+id/data_avaliacao"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/padrao_formato_data_hora"
android:textSize="14sp"
android:textColor="#color/colorPrimaryLight"
android:textAlignment="center"
/>
</LinearLayout>
<TextView
android:id="#+id/texto_sem_secoes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/container_titulo_avaliacao"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="16sp"
android:text="#string/nenhuma_secao_criada"
android:textColor="#color/colorPrimaryLight"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/secaoRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#+id/container_titulo_avaliacao"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout></androidx.constraintlayout.widget.ConstraintLayout>
Logcat loop from secaoList at the SecaoAdapter (is looping correctly to all elements):
I create a gif to show what is happening with the elements on recyclerView:
Here you can see that it displays seventh element then eighth is replaced by nineth and subsequently replaced by tenth. And final two elements (that should be ninth and tenth) is constructed with first and second list elements.
Thanks for the help in advance.
So the mistake here is that you are referencing only one binding in your adapter which is getting overwritten. Every time you call onCreateViewHolder you are changing the binding reference. The reason this looks okay to start with is that the onCreateViewHolder calls are followed by the onBindViewHolder calls for items visible on the screen. However as you scroll, just onBindViewHolder is called in order to rebind the recycled views.
What you should be doing is using your ViewHolder to store the individual bindings and then obtaining a reference in onBindViewHolder with something like holder.binding.
I would recommend you have a read into the view holder pattern and how to implement it!
I'm using RecyclerView to display a list of items.
Dependent on the specific item, i want to show additional views in the cell.
I know the viewholder should be static, but how do i achieve a cell design that depends on the properties of the item?
Minified example, which gives me weird results:
class CustomAdapter internal constructor() :
RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
private var dataSet = emptyList()
inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val title: TextView
val linearLayout: LinearLayout
init {
title = v.findViewById(R.id.textView)
linearLayout = v.findViewById(R.id.linearLayout)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.cardview, viewGroup, false)
return ViewHolder(v)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.title.text = dataSet[position].name
for (i in 0 until 5) {
viewHolder.linearLayout.addView(ImageView())
}
}
internal fun setItems(items: List<T>) {
this.dataSet = items
notifyDataSetChanged()
}
}
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="22dp"
android:layout_marginEnd="12dp"
android:text="Title"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</androidx.cardview.widget.CardView>
You can't add an ImageView directly as shown in your example. Try this:
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.title.text = dataSet[position].name
for (i in 0 until 5) {
val holder = viewHolder
val context = holder.itemView.context
val imagebyCode = ImageView(context)
imagebyCode.setImageResource(R.drawable.exampleImage)
val params : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
imagebyCode.layoutParams = params
val myLayout : LinearLayout = holder.itemView.findViewById(R.id.linearLayout)
myLayout.addView(imagebyCode)
}
}
You can add views to the xml for the recycler view row and keep the visibility hidden.
In onBindViewHolder you can check the condition and make the View visible.
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.title.text = dataSet[position].name
for (i in 0 until 5) {
viewHolder.linearLayout.view.visibility = View.VISIBLE //Set visibility here
}
}
I am new to android studio and just starter 1 month ago for learning it.
I currently try to written the app that has list of data class with name, price, quantity and unit cost.
I have done the recycle view and i am facing the problem that how to update the editText value whenever the user input the quantity in the data classs
Below are my data class code
data class food (val food: String, val price: Int, var quantity: Int, var cost: Int = price*quantity)
object ABC {
var food_List = listOf<food>(
ABC ("A", 28 ,5) ,
ABC ("B", 28, 0)
)}
Below are my recycle view adaptor
class customAdaptor (val context: Context, val food_List:List<food>):RecyclerView.Adapter<customAdaptor.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(context).inflate(R.layout.list_layout,parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return food_List.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val listused= food_List[position]
holder.setData(listused,position)
}
inner class ViewHolder (itemView: View): RecyclerView.ViewHolder(itemView) {
fun setData(listused: food?, pos: Int) {
itemView.listFoodName.text = listused!!.food
itemView.listUnitPrice.text =listused.price.toString()
itemView.listUnitTotalPrice.text=listused.cost.toString()
}
}}
Below are my mainactivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_page_budget)
val layoutManager = LinearLayoutManager(this)
layoutManager.orientation = LinearLayoutManager.VERTICAL
recyclerview.layoutManager = layoutManager
val adapter = customAdaptor(this, ABC.food_List)
recyclerview.adapter = adapter}
Below are my layout for card view.
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="270dp"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/listFoodName"/>
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/listUnitPrice"/>
<EditText
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textAlignment="center"
android:inputType="numberDecimal"
android:id="#+id/listQuantity"/>
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/listUnitTotalPrice"/> -->
</LinearLayout>
</androidx.cardview.widget.CardView>
Then i didnt know how to write the editText for the update.
Please help. Thank you very much.
You should use this:
editText.afterTextChanged{doSomethingWithText(it)}
Your code would be something like:
fun setData(listused: food?, pos: Int) {
itemView.listFoodName.text =listused!!.food
itemView.listUnitPrice.text =listused.price.toString()
itemView.listUnitTotalPrice.text=listused.cost.toString()
itemView.listQuantity.afterTextChanged {
listused?.quantity = it.toInt()
itemView.listUnitTotalPrice.text=listused.cost.toString()
}
}