I have implemented a custom adapter in a ListView but when i try to use setOnItemClickListener the function does not work. I tried using a toast to notify me if the click respond but it did not work
Here is my activity and the adapter
class PasswordListActivity : AppCompatActivity() {
private lateinit var dataSource: SavedPasswordDB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_password_list)
user = intent.getSerializableExtra("loggedUser") as User
loadPasswords()
btAddOpt.setOnClickListener {
// ...
}
}
override fun onPause() {
super.onPause()
this.loadPasswords()
}
override fun onResume() {
super.onResume()
this.loadPasswords()
}
internal class CustomAdapter(context: Context, data: List<SavedPassword>): ArrayAdapter<SavedPassword>(context, R.layout.activity_password_list, data) {
#SuppressLint("ViewHolder", "SetTextI18n")
private lateinit var dataSource: SavedPasswordDB
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = LayoutInflater.from(context).inflate(R.layout.custom_row, parent, false)
val pwd = getItem(position)
dataSource = SavedPasswordDB(context)
inflater.tvTitle.text = pwd!!.fromTitle
inflater.tvUser.text = "User: " + pwd.pwdUser
inflater.tvCont.text = "Password: " + pwd.pwdContent
inflater.tvOptLink.text = "Site link: " + pwd.optionalLink
inflater.tvCreated.text = "Created At: " + pwd.createdAt
inflater.btDeleteCurrent.setOnClickListener {
// ...
}
return inflater
}
}
private fun loadPasswords () {
dataSource = SavedPasswordDB(this)
var passwords = mutableListOf<SavedPassword>()
val cursor = dataSource.selectPwdByUser(user.id)
while (cursor.moveToNext()) {
val col = SavedPassword(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getInt(6))
passwords.add(col)
}
val adapter = CustomAdapter(this, passwords)
lvPwds.adapter = adapter
lvPwds.setOnItemClickListener { adapterView, view, i, id ->
val intent = Intent(this, PasswordDetailActivity::class.java)
startActivity(intent)
}
}
}
Also, i was thinking that the error could be in the XML files, maybe there is a property that im missging, so here they are:
ListView Activity:
<ListView
android:id="#+id/lvPwds"
android:layout_width="353dp"
android:layout_height="593dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btAddOpt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.87"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.90999997"
android:src="#drawable/add_icon"/>
Custom Adapter:
<LinearLayout
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:padding="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="160dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="260dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvTitle"
android:layout_width="35dp"
android:layout_height="wrap_content"
android:text="#string/site"
android:textColor="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.046"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvUser"
android:layout_width="61dp"
android:layout_height="wrap_content"
android:text="#string/userc"
app:layout_constraintStart_toStartOf="#+id/tvTitle"
app:layout_constraintTop_toBottomOf="#+id/tvTitle" />
<TextView
android:id="#+id/tvCont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/content"
app:layout_constraintStart_toStartOf="#+id/tvTitle"
app:layout_constraintTop_toBottomOf="#+id/tvTitle" />
<TextView
android:id="#+id/tvOptLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/optional_link"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#+id/tvTitle"
app:layout_constraintTop_toBottomOf="#+id/tvCont"
app:layout_constraintVertical_bias="0.043" />
<TextView
android:id="#+id/tvCreated"
android:layout_width="wrap_content"
android:layout_height="27dp"
android:text="#string/created_at"
app:layout_constraintStart_toStartOf="#+id/tvUser"
app:layout_constraintTop_toBottomOf="#+id/tvUser" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageButton
android:id="#+id/btDeleteCurrent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.952"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_delete" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Add below line to your ListViewtag in xml -
android:descendantFocusability="blocksDescendants"
It will help you.
Related
I am working on an application with multiple recycler views inside a fragment. Everything is working properly, except from one recycler view which doesn't display all data. I get the data after an API call, and I have already checked that they are loaded successfully. Any help would be much appreciated, thank you in advance!!
Here is the recycler view inside the fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#color/white"
tools:context=".ui.fragments.ExploreFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fillViewport="true"
android:scrollbars="none">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvExploreFragmentFeaturedProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Here is the cardview which will be loaded repeatedly inside the recycler view, which is not properly displayed (only the image view and shapeable image view gets displayed):
<?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:id="#+id/layoutFeaturedProductRowCardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
android:layout_marginBottom="40dp">
<RelativeLayout
android:id="#+id/rlFeaturedProducts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_frame_recommproducts_explore">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/ivFeaturedProduct"
android:layout_width="335dp"
android:layout_height="180dp"
android:scaleType="centerCrop"
app:shapeAppearanceOverlay="#style/rounded_cornersTop"
tools:src="#tools:sample/backgrounds/scenic" />
<ImageView
android:id="#+id/imageViewFavorite"
android:layout_width="wrap_content"
android:layout_height="26dp"
android:layout_alignEnd="#id/ivFeaturedProduct"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:src="#drawable/ic_favorite_up"/>
<TextView
android:id="#+id/textViewProductTitle"
android:layout_width="295dp"
android:layout_height="wrap_content"
android:layout_below="#+id/ivFeaturedProduct"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="16sp" />
<TextView
android:id="#+id/textViewCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewProductTitle"
android:layout_alignStart="#id/textViewProductTitle"
android:fontFamily="#font/semibold"
android:textSize="12sp"/>
<TextView
android:id="#+id/textViewDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewCategory"
android:layout_alignStart="#id/textViewCategory"
android:layout_marginTop="20dp"
android:drawablePadding="10dp"
android:fontFamily="#font/medium"
android:text="#string/durationlabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp"
app:drawableLeftCompat="#drawable/ic_time_icon" />
<TextView
android:id="#+id/textViewDurationValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/textViewDuration"
android:layout_alignBaseline="#id/textViewDuration"
android:layout_marginStart="2dp"
android:fontFamily="#font/medium"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="12sp"/>
<TextView
android:id="#+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewDuration"
android:layout_alignStart="#id/textViewDuration"
android:layout_marginTop="12dp"
android:drawablePadding="10dp"
android:fontFamily="#font/medium"
android:text="#string/languagelabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp"
app:drawableLeftCompat="#drawable/ic_audio_icon" />
<TextView
android:id="#+id/textViewLanguageValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/textViewLanguage"
android:layout_alignBaseline="#id/textViewLanguage"
android:layout_marginStart="2dp"
android:fontFamily="#font/medium"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="12sp" />
<TextView
android:id="#+id/textViewThreeSixtyImages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewLanguage"
android:layout_alignStart="#id/textViewLanguage"
android:layout_marginTop="12dp"
android:drawablePadding="10dp"
android:fontFamily="#font/medium"
android:text="#string/theesixtylabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp"
app:drawableLeftCompat="#drawable/ic_images_icon"
android:visibility="gone"/>
<TextView
android:id="#+id/ratingLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/ratingValue"
android:layout_toStartOf="#id/ratingValue"
android:layout_marginTop="2dp"
android:drawablePadding="10dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="14sp"
app:drawableLeftCompat="#drawable/ic_rating_small_tag" />
<TextView
android:id="#+id/ratingValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toStartOf="#id/ratingCount"
android:layout_alignBaseline="#id/ratingCount"
android:layout_marginEnd="2dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="14sp"
/>
<TextView
android:id="#+id/ratingCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ivFeaturedProduct"
android:layout_alignTop="#id/textViewCategory"
android:layout_alignRight="#id/ivFeaturedProduct"
android:layout_marginEnd="15dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="14sp" />
<TextView
android:id="#+id/priceLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ratingCount"
android:layout_alignEnd="#id/ratingCount"
android:layout_marginTop="20dp"
android:fontFamily="#font/medium"
android:text="#string/fromLabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp" />
<TextView
android:id="#+id/salesValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/priceLabel"
android:layout_below="#id/priceLabel"
android:layout_marginTop="2dp"
android:fontFamily="#font/medium"
android:textSize="12sp"
android:textColor="#color/colorPrimaryV2"
android:visibility="gone"/>
<TextView
android:id="#+id/priceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/priceLabel"
android:layout_alignEnd="#id/priceLabel"
android:layout_marginTop="18dp"
android:fontFamily="#font/bold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="18sp" />
<TextView
android:id="#+id/perPersonLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/priceValue"
android:layout_alignBaseline="#id/textViewThreeSixtyImages"
android:layout_alignEnd="#+id/priceValue"
android:fontFamily="#font/medium"
android:layout_marginBottom="24dp"
android:text="#string/perPersonLabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Then, here is the adapter giving the card view the values:
class ProductsAdapter(private val products: List<Product>) :
RecyclerView.Adapter<ProductsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.view_layout_featuredproduct_row, parent, false)
view.layoutParams.height = (parent.measuredWidth - 40)/2 + 30
view.requestLayout()
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindProduct(products[position])
}
override fun getItemCount(): Int = products.size
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val image = view.findViewById<ShapeableImageView>(R.id.ivFeaturedProduct)
private val featuredProductTitle = view.findViewById<TextView>(R.id.textViewProductTitle)
private val category = view.findViewById<TextView>(R.id.textViewCategory)
private val featuredProductDuration = view.findViewById<TextView>(R.id.textViewDurationValue)
private val language = view.findViewById<TextView>(R.id.textViewLanguageValue)
private val averageRating = view.findViewById<TextView>(R.id.ratingValue)
private val ratingcount = view.findViewById<TextView>(R.id.ratingCount)
private val pricevalue = view.findViewById<TextView>(R.id.priceValue)
private val context = view.context
private val resources = view.resources
fun bindProduct(product: Product) {
with(product) {
val uri = this.header_image
Picasso.get().load(uri).
placeholder( R.drawable.progress_animation ).
transform(ColorFilterTransformation(ContextCompat.getColor(context, R.color.colorOverlay))).
into(image)
val categoryHelper = this.sku
if (categoryHelper[0].equals('S')){
category.text = resources.getString(R.string.skipTheLineTours)
category.setBackgroundResource(R.drawable.label_skipthelinetour)
category.setTextColor(resources.getColor(R.color.colorSkipTheLineTourTxt))
}
if (categoryHelper[0].equals('A')){
category.text = resources.getString(R.string.audioTours)
category.setBackgroundResource(R.drawable.label_audiotour)
category.setTextColor(resources.getColor(R.color.colorAudioTourTxt))
}
if(categoryHelper[0].equals('V')){
category.text = resources.getString(R.string.virtualTours)
category.setBackgroundResource(R.drawable.label_virtualtour)
category.setTextColor(resources.getColor(R.color.colorVirtualTourTxt))
}
featuredProductTitle.text = this.title
featuredProductDuration.text = this.duration+" minutes"
language.text = languages.size.toString()+" languages"
//category.text = this.sku
averageRating.text = this.average_rating
ratingcount.text = "("+this.rating_count.toString()+")"
pricevalue.text = this.retail_price.toString()+"€"
}
}
}
}
And last but not least, here is the code generating the recycler view:
class ExploreFragment : Fragment() {
private lateinit var viewProductsAdapter: ProductsAdapter
private val model: ProductsViewModel by activityViewModels()
private lateinit var featuredProducts: MutableList<Product>
private lateinit var viewManager : LinearLayoutManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_explore, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
loadFeaturedProducts()
}
private fun loadFeaturedProducts() {
if(!NetworkState().isNetworkAvailable(this#ExploreFragment.context!!.applicationContext)){
return;
}
featuredProducts = mutableListOf()
val recyclerView = rvExploreFragmentFeaturedProducts
viewProductsAdapter = ProductsAdapter(this.featuredProducts)
viewManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
recyclerView.layoutManager = viewManager
//recyclerView.setHasFixedSize(true)
recyclerView.adapter = viewProductsAdapter
Timber.i("Fragment: load featured products")
model.getProducts().observe(viewLifecycleOwner, { products->
if(products.status == Status.SUCCESS) {
this.featuredProducts.addAll(products.data!!)
viewProductsAdapter.notifyDataSetChanged()
}else {
Timber.i("Featured Products message: "+products.message)
Snackbar.make(view!!, "Cannot load featured products! Error:"+products.message, Snackbar.LENGTH_LONG).show()
}
})
}
}
Thank you for your answers - I figured out my mistake:
I couldn't see anything that was below the ImageView inside my CardView, even though it loaded correctly.
On ProductsListAdapter I forgot to remove an unnecessary calculation:
view.layoutParams.height = (parent.measuredWidth - 40)/2 + 30
view.requestLayout()
which was what caused the problem!
Instead of using the following code:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvExploreFragmentFeaturedProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
>
</androidx.recyclerview.widget.RecyclerView>
Please update it with
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvExploreFragmentFeaturedProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
/>
the Reason you are not getting data is tags! You are not closing tag of Recycler View instead you are creating a new scope to add more things in it like we do with Layouts.
So remove : </androidx.recyclerview.widget.RecyclerView> and add "/" to the closing tag of recycler view or just simply copy and paste my code above
In my app I load data from API which is using paginating so I have to use paging 3 library
and I use facebook shimmer library to show shimmer effect when items are being loaded
but the problem is always shimmer effect is shown even when items are completely loaded
ArticlePagingAdapter.kt
class ArticlePagingAdapter(private val listener: OnItemClickListener) :
PagingDataAdapter<Article, ArticlePagingAdapter.ViewHolder>(ArticleDiffUtil()) {
private val TAG = ArticlePagingAdapter::class.simpleName
private lateinit var context: Context
var showShimmer: Boolean = true
inner class ViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView), View.OnClickListener {
lateinit var item: Article
val shimmerLayout: ShimmerFrameLayout = itemView.shimmer_layout
val articleImageView: ShapeableImageView = itemView.findViewById(R.id.article_image_view)
val articleTitleTextView: TextView = itemView.findViewById(R.id.article_title_text_view)
val articleEstimatedTextView: TextView =
itemView.findViewById(R.id.article_estimated_read_time_text_view)
val clockImageView: ImageView = itemView.findViewById(R.id.clock_icon)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (showShimmer) {
holder.shimmerLayout.startShimmer()
} else {
holder.shimmerLayout.stopShimmer()
holder.shimmerLayout.setShimmer(null)
holder.articleImageView.background = null
holder.clockImageView.background = null
holder.articleEstimatedTextView.background = null
holder.articleTitleTextView.background = null
val item = getItem(position)
if (item != null) {
Log.d(TAG, "position $position, isNull != null ")
holder.item = item
holder.articleTitleTextView.text = item.title
holder.articleEstimatedTextView.text = (item.estimatedReadingTime.toString()
val requestOptions = RequestOptions().transform(
CenterCrop(), RoundedCorners(
context.resources.getDimension(R.dimen.item_article_image_view_radius)
.toInt()
)
)
Glide.with(context).load(item.imageUrl!!.toUri())
.placeholder(R.drawable.ic_article_placeholder).apply(requestOptions)
.into(holder.articleImageView)
holder.clockImageView.setImageResource(R.drawable.ic_clock)
} else {
Log.d(TAG, "position $position, isNull= null ")
}
}
}
}
ArticleFragmnet.kt
class LatestArticlesFragment : Fragment(), ArticlePagingAdapter.OnItemClickListener {
val TAG = LatestArticlesFragment::class.simpleName
lateinit var binding: FragmentLatestArticlesBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// some unrelated code
val adapter = ArticlePagingAdapter(this)
binding.recyclerView.adapter = adapter
viewModel.getArticles().observe(viewLifecycleOwner) { data ->
lifecycleScope.launch {
adapter.submitData(data)
Log.d(TAG,"data ${data.toString()}")
adapter.showShimmer = false
}
}
}
}
ArticleFragmentViewModel.kt
class LatestArticlesFragmentViewModel #AssistedInject constructor(
private val repository: ArticleRepository, ...) : ViewModel() {
fun getArticles(): LiveData<PagingData<Article>> {
currentArticles = repository.getArticlesStream().cachedIn(viewModelScope)
return currentArticles?.asLiveData()!!
}
}
item_article.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView 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"
style="#style/card_view_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/small_margin"
android:clipToPadding="false"
android:paddingBottom="#dimen/_2sdp">
<com.facebook.shimmer.ShimmerFrameLayout
android:id="#+id/shimmer_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/very_small_padding">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/article_image_view"
android:layout_width="0dp"
android:layout_height="#dimen/_70sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="3:2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/article_title_text_view"
app:layout_constraintTop_toTopOf="parent"
tools:src="#drawable/ic_icon" />
<TextView
android:id="#+id/article_title_text_view"
style="#style/Widget.MyWidget.TextView.VerySmall.Bold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/very_small_margin"
android:layout_marginEnd="#dimen/very_small_margin"
android:ellipsize="end"
android:gravity="start"
android:maxLines="2"
android:minLines="2"
android:textAlignment="textStart"
android:textColor="?attr/textColor"
app:layout_constraintBottom_toTopOf="#id/clock_icon"
app:layout_constraintEnd_toStartOf="#id/article_image_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#id/article_image_view"
tools:text="This is a dummy title" />
<TextView
android:id="#+id/article_estimated_read_time_text_view"
style="#style/Widget.MyWidget.TextView.VerySmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/very_small_margin"
android:background="#color/shimmer_background"
android:textColor="?attr/textColor"
app:layout_constraintBottom_toBottomOf="#id/article_image_view"
app:layout_constraintEnd_toEndOf="#id/article_title_text_view"
app:layout_constraintStart_toEndOf="#id/clock_icon"
app:layout_constraintTop_toBottomOf="#id/article_title_text_view"
tools:text="5 min" />
<ImageView
android:id="#+id/clock_icon"
android:layout_width="#dimen/_10sdp"
android:layout_height="#dimen/_10sdp"
android:background="#color/shimmer_background"
app:layout_constraintBottom_toBottomOf="#id/article_estimated_read_time_text_view"
app:layout_constraintEnd_toStartOf="#id/article_estimated_read_time_text_view"
app:layout_constraintStart_toStartOf="#id/article_title_text_view"
app:layout_constraintTop_toTopOf="#id/article_estimated_read_time_text_view"
tools:src="#drawable/ic_clock" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.facebook.shimmer.ShimmerFrameLayout>
</com.google.android.material.card.MaterialCardView>
fragment_article_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/root_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/articleBackground">
<TextView
android:id="#+id/article_text_view"
style="#style/Widget.MyWidget.TextView.Large.Bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/medium_margin"
android:text="#string/articles"
android:textColor="?attr/textColor"
app:layout_constraintStart_toStartOf="#id/left_guideline"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/line_separator"
style="#style/Divider"
android:layout_marginStart="#dimen/_10sdp"
app:layout_constraintBottom_toBottomOf="#id/article_text_view"
app:layout_constraintEnd_toEndOf="#id/right_guideline"
app:layout_constraintStart_toEndOf="#id/article_text_view"
app:layout_constraintTop_toTopOf="#id/article_text_view"
app:layout_constraintVertical_chainStyle="packed" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#android:color/transparent"
android:clipToPadding="false"
android:orientation="vertical"
android:paddingHorizontal="#dimen/small_padding"
android:paddingTop="#dimen/small_padding"
android:paddingBottom="#dimen/small_padding"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#id/article_text_view"
tools:itemCount="8"
tools:listitem="#layout/item_article" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="?attr/listFadeBackground"
app:layout_constraintTop_toTopOf="#id/recycler_view" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/left_guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.03" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/right_guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.97" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
I am loading in Data from Cloud Firestore. That data is then being added as an Item to a RecyclerView and should be displayed on the screen. However, the RecyclerView remains empty.
The data is loaded in correctly from Cloud Firestore (I can tell because of the logs I added which are shown below).
So I cannot find out why the data is not being added to the RecyclerView correctly and displayed?
ActiveOrderActivity.kt
class ActiveOrderActivity : AppCompatActivity() {
private val aorderList = ArrayList<ActiveOrderModel>()
private val adapter = AOrdersAdapter(aorderList)
/* Access a Cloud Firestore instance from the Activity. */
val db = Firebase.firestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_active_order)
recyclerview.adapter = adapter
recyclerview.layoutManager = LinearLayoutManager(this)
recyclerview.setHasFixedSize(true)
db.collection("Orders - 18.3.2021")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.i("", "IN LOOP FOR DOCUMENT: ActiveOrderActivity.\n")
val customerName = document.getField<String>("customer Name")
Log.i("", "$customerName: ActiveOrderActivity.\n")
val customerNumber = document.getField<String>("customer Number")
val customerPostal = document.getField<String>("eircode")
val customerAddress = document.getField<String>("address")
val paymentAmount = document.getField<String>("payment Amount")
val paymentType = document.getField<String>("payment Total")
val newItem = ActiveOrderModel(customerName = customerName,customerNumber = customerNumber,customerPostal = customerPostal,customerAddress = customerAddress,paymentAmount = paymentAmount,paymentType = paymentType)
aorderList.add(INDEX,newItem)
adapter.notifyItemInserted(INDEX)
}
}
}
}
AOrdersAdapter.kt
class AOrdersAdapter(private val aorderList: List<ActiveOrderModel> ) : RecyclerView.Adapter<AOrdersAdapter.AOrderViewHolder>() {
class AOrderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val nameView = view.nameView
val addressView = view.address1View
val mobileView = view.mobileView
val eircodeView = view.eircodeView
val paymentView = view.paymentView
val paymentAmountView = view.paymentAmountView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AOrderViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.active_order_item, parent, false)
return AOrderViewHolder(view)
}
override fun getItemCount(): Int {
return aorderList.size
}
override fun onBindViewHolder(holder: AOrderViewHolder, position: Int) {
val currentItem = aorderList[position]
holder.nameView.text = currentItem.customerName
holder.addressView.text = currentItem.customerNumber
holder.mobileView.text = currentItem.customerPostal
holder.eircodeView.text = currentItem.customerAddress
holder.paymentAmountView.text = currentItem.paymentAmount
holder.paymentView.text = currentItem.paymentType
}
}
activity_active_order.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"
tools:context=".MainBody.dashboard.ordersActivites.ActiveOrderActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="wrap_content"
android:layout_height="699dp"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:clipToPadding="false"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/floatingActionButton"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/active_order_item" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/floatingActionButton"
android:layout_width="307dp"
android:layout_height="68dp"
android:layout_marginTop="88dp"
android:background="#drawable/pizaa_button2"
android:text="Main Menu"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
active_order_item.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:id="#+id/rowConstraintLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<androidx.cardview.widget.CardView
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_toTopOf="parent"
android:padding="16dp"
android:layout_margin="4dp"
app:cardElevation="10dp"
app:cardCornerRadius="8dp"
app:cardPreventCornerOverlap="false">
<RelativeLayout
android:layout_width="800dp"
android:layout_height="match_parent"
android:padding="12dp">
<TextView
android:id="#+id/nameView"
android:layout_width="223dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="6dp"
android:layout_marginEnd="0dp"
android:text="George Matthews"
android:textColor="#color/shopColour"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/address1View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nameView"
android:layout_alignParentStart="true"
android:layout_marginStart="6dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="6dp"
android:text="123 Fakelands,\nHigher up Road,\nDublin"
android:textColor="#color/logoYellow"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/mobileView"
android:layout_width="144dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/productPriceView"
android:layout_marginStart="20dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="100dp"
android:layout_toEndOf="#+id/nameView"
android:text="089 215 2121"
android:textColor="#color/shopColour"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/eircodeView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_below="#+id/mobileView"
android:layout_alignEnd="#+id/mobileView"
android:layout_marginStart="43dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="11dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="1dp"
android:layout_toEndOf="#+id/nameView"
android:text="A96 K4D8"
android:textColor="#color/logoYellow"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/paymentView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/productPriceView"
android:layout_marginStart="20dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="100dp"
android:layout_toEndOf="#+id/mobileView"
android:gravity="center"
android:text="Frank's Website"
android:textColor="#color/shopColour"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/paymentAmountView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/paymentView"
android:layout_alignEnd="#+id/paymentView"
android:layout_marginStart="144dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="-5dp"
android:layout_marginBottom="1dp"
android:layout_toEndOf="#+id/eircodeView"
android:gravity="center"
android:text="47.00"
android:textColor="#color/logoYellow"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
ActiveOrderModel.kt
data class ActiveOrderModel(
val customerName: String? = null,
val customerNumber: String? = null,
val customerPostal: String? = null,
val customerAddress: String? = null,
val paymentAmount: String? = null,
val paymentType: String? = null )
Here the running terminal shows that the data has been loaded correctly from the Cloud Firestore and the loop is working to iterate through all the entries in the Collection. Now each document should be added to the RecyclerView but the Recycler View is empty as shown below.
You need to update list in adapter to get desired result. Create a method in adapter as below -
fun updateList(list: List<ActiveOrderModel> ) {
this.aorderList = list
notifyDataSetChanged()
}
Update below lines in your activity
aorderList.add(INDEX,newItem)
adapter.updateList(aorderList)
adapter.notifyItemInserted(INDEX)
try this
fun initRecyclerView() {
mainRecycler.setLayoutManager(LinearLayoutManager(context))
var linearLayoutManager: LinearLayoutManager? = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mainRecycler?.layoutManager = linearLayoutManager
val itemDecorator = VerticalSpacingItemDecorator(20)
mainRecycler.addItemDecoration(itemDecorator)
adapter = AOrdersAdapter(aorderList)
mainRecycler.setAdapter(adapter)
}
and this
for (document in result) {
Log.i("", "IN LOOP FOR DOCUMENT: ActiveOrderActivity.\n")
val customerName = document.getField<String>("customer Name")
Log.i("", "$customerName: ActiveOrderActivity.\n")
val customerNumber = document.getField<String>("customer Number")
val customerPostal = document.getField<String>("eircode")
val customerAddress = document.getField<String>("address")
val paymentAmount = document.getField<String>("payment Amount")
val paymentType = document.getField<String>("payment Total")
val newItem = ActiveOrderModel(customerName = customerName,customerNumber = customerNumber,customerPostal = customerPostal,customerAddress = customerAddress,paymentAmount = paymentAmount,paymentType = paymentType)
aorderList.add(INDEX,newItem)
adapter.notifyItemInserted(INDEX)
}
adapter?.notifyDataSetChanged()
use adapter?.notifyDataSetChanged()
and must check your arraylist not be empty.
I am trying to make a grid layout with expandable cards, but the problem is that when a card is expanded, its height gets bigger and so does the height of the other cards in the row (to match the height of the first card), but when the card is collapsed back, the height of all the cards does not change as if they were expanded. Anyone knows what could be the problem?
EDIT :
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView 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/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#color/misty_rose"
android:layout_margin="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Media -->
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="center_horizontal"
android:padding="8dp"
android:contentDescription="Photo"
android:src="#drawable/unsplash"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#color/isabelline"
/>
<!-- Title, secondary and supporting text -->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/misty_rose"
app:layout_constraintTop_toBottomOf="#+id/imageView"
android:padding="8dp">
<TextView
android:id="#+id/textViewCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Code"
android:textAppearance="?attr/textAppearanceHeadline6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatImageButton
android:id="#+id/iconExpandCard"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:padding="8dp"
android:src="#drawable/ic_baseline_expand_more_36"
android:background="?attr/selectableItemBackgroundBorderless"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/textViewDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Description"
android:textAppearance="?attr/textAppearanceBody1"
android:textColor="?android:attr/textColorSecondary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textViewCode" />
<TextView
android:id="#+id/textViewPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Price"
android:textAppearance="?attr/textAppearanceBody1"
android:textColor="?android:attr/textColorSecondary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textViewDescription"/>
<TextView
android:id="#+id/textViewComment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Comment"
android:textAppearance="?attr/textAppearanceBody1"
android:textColor="?android:attr/textColorSecondary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textViewPrice"
android:visibility="gone"/>
<!-- Buttons -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textViewComment">
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonMinusArticle"
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:width="88dp"
android:minWidth="40dp"
android:backgroundTint="#color/purple_200"
android:text="#string/minus"
android:textColor="#color/white" />
<EditText
android:id="#+id/editNumberOfProducts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="16dp"
android:inputType="numberDecimal|number"
android:text="#string/zero"
android:textAppearance="?attr/textAppearanceBody1"
android:textColor="?android:attr/textColorSecondary"
android:textSize="18sp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonPlusArticle"
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="88dp"
android:minWidth="40dp"
android:backgroundTint="#color/purple_200"
android:text="#string/plus"
android:textColor="#color/white" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
And in ProductListAdapter.kt (the important part is in expandButton.setOnClickListener() ):
class ProductListAdapter() : ListAdapter<Product, ProductListAdapter.ProductViewHolder>(ProductsComparator()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
return ProductViewHolder.create(parent)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val current = getItem(position)
holder.bind(current!!)
}
class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val productItemView: TextView = itemView.findViewById(R.id.textViewCode)
private val productDescription : TextView = itemView.findViewById(R.id.textViewDescription)
private val productPrice : TextView = itemView.findViewById(R.id.textViewPrice)
fun bind(product: Product) {
productItemView.text = product.code
//productDescription.text = product.description
//productPrice.text = "Price " + product.client_price.toString()
}
companion object {
val mapOfProducts :HashMap<String, Int> = hashMapOf<String, Int>()
fun create(parent: ViewGroup): ProductViewHolder {
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.recyclerview_item, parent, false)
val minusButton : Button = view.findViewById(R.id.buttonMinusArticle)
val plusButton : Button = view.findViewById(R.id.buttonPlusArticle)
val productItemViewCode: TextView = view.findViewById(R.id.textViewCode)
val expandButton : androidx.appcompat.widget.AppCompatImageButton = view.findViewById(R.id.iconExpandCard)
val commentView : TextView = view.findViewById(R.id.textViewComment)
val cardView : CardView = view.findViewById(R.id.cardView)
expandButton.setOnClickListener{
if (commentView.visibility == View.GONE){
TransitionManager.beginDelayedTransition(cardView, AutoTransition())
commentView.visibility = View.VISIBLE
expandButton.setImageResource(R.drawable.ic_baseline_expand_less_36)
} else {
TransitionManager.beginDelayedTransition(cardView, AutoTransition())
commentView.visibility = View.GONE
expandButton.setImageResource(R.drawable.ic_baseline_expand_more_36)
}
}
val editNumberOfProducts: EditText = view.findViewById(R.id.editNumberOfProducts)
editNumberOfProducts.doAfterTextChanged {
val code = productItemViewCode.text.toString()
if (it.isNullOrBlank()) {
modifyText("0", view)
mapOfProducts.remove(code)
return#doAfterTextChanged
}
val originalText = it.toString()
try {
val number = originalText.toInt()
val numberText = originalText.toInt().toString()
if (originalText != numberText) {
modifyText(numberText, view)
}
if (number > 0) {
mapOfProducts[code] = number
d("CodeOfView", "$code $number")
}else {
mapOfProducts.remove(code)
}
} catch (e: Exception) {
modifyText("0", view)
mapOfProducts.remove(code)
}
}
minusButton.setOnClickListener {
var number = editNumberOfProducts.text.toString().toInt()
if (number>0) {
number -= 1
modifyText(number.toString(), view)
}
}
plusButton.setOnClickListener {
//val code = productItemViewCode.text.toString()
var number = editNumberOfProducts.text.toString().toInt()
number += 1
modifyText(number.toString(), view)
}
return ProductViewHolder(view)
}
private fun modifyText(numberText: String, view: View) {
val editNumberOfProducts = view.findViewById<EditText>(R.id.editNumberOfProducts)
editNumberOfProducts.setText(numberText)
editNumberOfProducts.setSelection(numberText.length)
}
}
}
class ProductsComparator : DiffUtil.ItemCallback<Product>() {
override fun areItemsTheSame(oldItem: Product, newItem: Product): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: Product, newItem: Product): Boolean {
return oldItem.code == newItem.code
}
}
}
Example with images of the problem
I was facing a same issue, in my case it was vertical expandable cards and I managed to solve it by using
Adapter.notifyDataSetChanged()
in the right place.
I'm new in app developpement and I have a problem with an EditText in recyclerview's item.
When user clicks on the editText nothing appens. I tried with an itemClickListener on EditText, click did worked but not edtion of text.
Here is my code :
the Activity :
class MyIngredientListActivity : AppCompatActivity() {
val ingerdientOfListArray = database.getAllIngredientOfList()
val adapter = IngredientOfListAdapter(ingerdientOfListArray)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.ingredient_list_recyclerview)
findViewById<Button>
(R.id.ingredient_list_activity_search_button).setOnClickListener {
val intent = Intent(this, IngredientSearchableActivity::class.java)
startActivity(intent)
}
val recyclerView = findViewById<RecyclerView>
(R.id.ingredientoflist_recyclerview)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
}
override fun onResume() {
super.onResume()
adapter.updateIngredientList()
}
The adapter :
class IngredientOfListAdapter(val ingredientOfListDisplay:
ArrayList<IngredientOfList>
): RecyclerView.Adapter<IngredientOfListAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cardView = itemView.findViewById<CardView>
(R.id.ingredientoflist_cardview_name)
val name = itemView.findViewById<TextView>(R.id.ingredientoflist_name)
val checkbox = itemView.findViewById<CheckBox>
(R.id.ingredientoflist_checkbox)
val editText = itemView.findViewById<EditText>
(R.id.ingredientoflist_quantity)
val unitmeasure = itemView.findViewById<TextView>
(R.id.ingredientoflist_unitmeasure)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val viewItem = inflater.inflate(R.layout.ingredient_list_item, parent, false)
return ViewHolder(viewItem)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val ingredientOfList = ingredientOfListDisplay[position]
val ingredientFromId = database.readIngredientById(ingredientOfList).first()
val unitMeasureId = database.readUnitMeasureById(ingredientFromId).first()
holder.cardView?.tag = position
holder.name.text = ingredientFromId.name
holder.unitmeasure.text = unitMeasureId.symbol
holder.editText?.tag = position
holder.editText.setText(0)
}
override fun getItemCount(): Int {
return ingredientOfListDisplay.size
}
fun updateIngredientList(ingredientOfListArray: ArrayList<IngredientOfList> = database.getAllIngredientOfList()) {
ingredientOfListDisplay.clear()
ingredientOfListDisplay.addAll(ingredientOfListArray)
notifyDataSetChanged()
}
}
RelativeLayout here
cardview here
android:id="#+id/ingredientoflist_cardview_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardUseCompatPadding="true"
android:focusable="false"
android:clickable="false"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C3FFFFFF">
<TextView
android:id="#+id/ingredientoflist_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:textColor="#403E3E"
android:textSize="17sp"
android:textStyle="bold"
tools:text="ingredient"/>
<EditText
android:id="#+id/ingredientoflist_quantity"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_alignParentBottom="true"
android:layout_marginStart="250dp"
android:layout_marginLeft="250dp"
android:layout_marginBottom="8dp"
android:clickable="true"
android:focusable="true"
android:inputType="number"
android:imeOptions="actionDone"
android:saveEnabled="true"
android:hint="00"
android:textColor="#403E3E"
android:textSize="17sp"
android:textStyle="bold"
android:gravity="center_horizontal"
android:background="#drawable/abc_vector_test" />
<TextView
android:id="#+id/ingredientoflist_unitmeasure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:layout_marginStart="305dp"
android:layout_marginLeft="305dp"
android:hint="cl"
android:textColor="#403E3E"
android:textSize="17sp"
android:textStyle="bold"/>
<CheckBox
android:id="#+id/ingredientoflist_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginStart="350dp"
android:layout_marginLeft="350dp"
android:gravity="center_vertical"/>
</RelativeLayout>
</CardView>
RecyclerView Layout:
<RelativeLayout
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"
style="#style/NoActionBar"
android:background="#000000">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="#+id/ingredient_search_activity_search_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:paddingBottom="60dp"
app:srcCompat="#drawable/baseline_no_food_white_48"
app:tint="#40FFFFFF" />
<Button
android:id="#+id/ingredient_search_activity_search_button"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#android:color/white"
android:drawableStart="#android:drawable/ic_search_category_default"
android:drawableLeft="#android:drawable/ic_search_category_default"
android:gravity="start|center_vertical"
android:text="#string/my_searchables_ingredients"
android:textAlignment="textStart"
android:focusable="false"
android:clickable="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/ingredientoflist_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C3FFFFFF"
app:queryHint="your ingredients"
android:layout_below="#id/ingredient_search_activity_search_button"
android:clickable="false"
android:focusable="false"/>
</RelativeLayout>
Thanks and have a good day !
I think adding
holder.editText.setOnClickListener(Object : View.OnClickListener {
override fun OnClick(v: View?) {
v.requestFocus()
}
}
Should do the trick. I'm not very good at Kotlin, so there might be a syntax error there.