Android LinearLayout Gone don't update automatically - android

I have a form that it could be submitted and send the data to an API, so when I receive the callback of request done I would like to hide the form and show a view of thanks.
This is my layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/thank_you_layout_rate"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone"
tools:ignore="UseCompoundDrawables">
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginTop="20dp"
android:src="#drawable/ic_check_circle_green_800_48dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginTop="5dp"
android:fontFamily="#font/roboto_medium"
android:gravity="center"
android:text="#string/thank_you_for_rating"
android:textAppearance="#android:style/TextAppearance.Material.Large"
android:textColor="#color/DarkBlue"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="#+id/form_rating"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="visible">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="0.1"
android:fontFamily="#font/roboto_medium"
android:gravity="center"
android:text="#string/rate_our_app"
android:textAppearance="#android:style/TextAppearance.Material.Large"
android:textColor="#color/DarkBlue"
android:textStyle="bold" />
<RatingBar
android:id="#+id/ratingbar_rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:isIndicator="false"
android:numStars="5"
android:rating="4"
android:stepSize="1" />
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="?android:attr/listDivider" />
<EditText
android:hint="#string/rate_our_app"
android:id="#+id/comment_rate"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.8"
android:inputType="textMultiLine"
android:textAppearance="#android:style/TextAppearance.Material.Large"
android:textColor="#color/DarkBlue"
/>
<Button
android:id="#+id/save_rate"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="15dp"
android:layout_weight="0.1"
android:background="#color/DecathlonBlue"
android:fontFamily="#font/roboto_medium"
android:gravity="center"
android:text="#string/save"
android:textAlignment="center"
android:textAppearance="#android:style/TextAppearance.Material.Large"
android:textColor="#color/LightGrey"
android:textAllCaps="true"/>
</LinearLayout>
</LinearLayout>
and this is my fragment :
class RateFragment : Fragment(), RateFragmentListener {
private lateinit var mLoginManager: LoginManager
private lateinit var loadingDialog: LoadingDialog
private lateinit var ratePresenter: RatePresenter
private lateinit var mView: View
private lateinit var rateNotAllowed: LinearLayout
private lateinit var formRating: LinearLayout
companion object {
fun newInstance(loginManager: LoginManager): Fragment {
val currentFragment = RateFragment()
currentFragment.mLoginManager = loginManager
return currentFragment
}
}
override fun onResume() {
this.stopLoadingDialog()
super.onResume()
}
/**
*
* #param inflater LayoutInflater
* #param container ViewGroup?
* #param savedInstanceState Bundle?
* #return View?
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
mView = inflater.inflate(R.layout.rate_fragment, container, false)
val saveButton = mView.findViewById<Button>(R.id.save_rate)
val starBar = mView.findViewById<RatingBar>(R.id.ratingbar_rate)
val commentRate = mView.findViewById<EditText>(R.id.comment_rate)
rateNotAllowed = mView.findViewById(R.id.thank_you_layout_rate)
formRating = mView.findViewById(R.id.form_rating)
loadingDialog = LoadingDialog(context!!)
startLoadingDialog()
initPresenter(activity as Activity, this)
saveButton.setOnClickListener {
this.startLoadingDialog()
ratePresenter.sendRating(
commentRate.text.toString(),
starBar.rating
)
}
return mView
}
/**
*
* #param activity Activity
*/
private fun initPresenter(
activity: Activity,
rateFragment: RateFragment
) {
ratePresenter = RatePresenter(activity, mLoginManager, rateFragment)
}
/**
* Loading dialog, block the UI
*/
override fun stopLoadingDialog() {
loadingDialog.dismiss()
}
/**
* Loading dialog, block de UI
*/
override fun startLoadingDialog() {
loadingDialog.show()
}
override fun rateSent() {
stopLoadingDialog()
}
override fun rateError() {
activity!!.toast("error on sending the rating")
stopLoadingDialog()
}
override fun rateNotAllowed() {
formRating.visibility = View.GONE
rateNotAllowed.visibility = View.VISIBLE
}
}
But the update of the view isn't done automatically only if I change the vie and come back to it ( there is an if inside the presenter that check if a note is sent or not ).
Thank you, regards

Related

RecyclerView doesn't show any items even though getItemCount() returns the correct count in the adapter

everyone. I have a RecyclerView in which I want to display items. For this I implemented an adapter class and the required functions. I have 3 identical example data sets which I pass to the adapter and which are also correctly displayed as 3 in getItemCount(). However, my problem is that I can't see anything. The RecyclerView remains empty. I also don't get any errors in the terminal/debugger, everything is correct. Have I made a mistake and perhaps forgot something?
Here is my OverviewActivity containing the RecyclerView:
class OverviewActivity : AppCompatActivity() {
private lateinit var resultsAdapter: ResultsAdapter
private lateinit var listResults : ArrayList<HouseModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_overview)
listResults = ArrayList()
var resultRv: RecyclerView = findViewById(R.id.result_rv)
resultRv.layoutManager = LinearLayoutManager(this)
resultsAdapter = ResultsAdapter(this, listResults)
resultRv.adapter = resultsAdapter
//TEST DATA
listResults.add(HouseModel("Abador",R.drawable.house,R.drawable.alle,"Bella Vista, PY","650","Schönes, neu renoviertes Haus. Mit neuestem Standard. Kann besichtigt werden"))
listResults.add(HouseModel("Abador",R.drawable.house,R.drawable.alle,"Bella Vista, PY","650","Schönes, neu renoviertes Haus. Mit neuestem Standard. Kann besichtigt werden"))
listResults.add(HouseModel("Abador",R.drawable.house,R.drawable.alle,"Bella Vista, PY","650","Schönes, neu renoviertes Haus. Mit neuestem Standard. Kann besichtigt werden"))
resultsAdapter.notifyDataSetChanged()
... } }
Model class:
data class HouseModel(
var senderName: String,
var mainImg : Int,
var senderImg: Int,
var place: String,
var price: String,
var desc: String,
)
ResultsAdapter:
class ResultsAdapter(private val context: Context, private val resultsList: ArrayList<HouseModel>): RecyclerView.Adapter<ResultsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResultsAdapter.ViewHolder {
val inflateView = LayoutInflater.from(context).inflate(R.layout.result_list_rv,parent,false)
return ViewHolder(inflateView)
}
class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
val mainImg: ImageView = view.findViewById(R.id.rv_list_main_img)
val senderImg: ImageView = view.findViewById(R.id.main_list_rv_sender_img)
val senderName: TextView = view.findViewById(R.id.main_list_rv_sender_name)
val place: TextView = view.findViewById(R.id.main_list_rv_place)
val desc: TextView = view.findViewById(R.id.main_list_rv_desc)
val price: TextView = view.findViewById(R.id.main_list_rv_price)
}
override fun onBindViewHolder(holder: ResultsAdapter.ViewHolder, position: Int) {
holder.mainImg.setImageResource(resultsList[position].mainImg)
holder.senderImg.setImageResource(resultsList[position].senderImg)
holder.senderName.text = resultsList[position].senderName
holder.place.text = resultsList[position].place
holder.desc.text = resultsList[position].desc
holder.price.text = resultsList[position].price
}
override fun getItemCount(): Int {
println("ITEMS: ${resultsList.size}")
// SHOWS I/System.out: ITEMS: 3
return resultsList.size
}
}
UPDATE
RecyclerView Code:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/result_rv"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp">
</androidx.recyclerview.widget.RecyclerView>
And my code for result_list_rv.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/rv_list_main_img"
android:src="#drawable/longtime"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginStart="20dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/main_list_rv_sender_img"
android:background="#drawable/imageborder"
android:padding="10dp"
android:src="#drawable/shorttime"
android:layout_width="100dp"
android:layout_height="100dp"></ImageView>
<TextView
android:id="#+id/main_list_rv_sender_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abador"
android:layout_marginTop="16dp"
android:fontFamily="#font/baumans"
android:textSize="23sp"
android:textStyle="bold"></TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical"
android:layout_gravity="bottom"
android:layout_marginEnd="20dp"
android:gravity="right">
<TextView
android:id="#+id/main_list_rv_place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bella Vista, PY"
android:textSize="16sp">
</TextView>
<TextView
android:id="#+id/main_list_rv_price"
android:layout_marginTop="20dp"
android:gravity="bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="600 USD/mtl"
android:textSize="23sp"
android:textStyle="bold"></TextView>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_gravity="center">
<TextView
android:id="#+id/main_list_rv_desc"
android:layout_width="260dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:gravity="left"
android:maxLength="200"
android:maxLines="2"
android:text="Beschreibung Haus sdf sdfe Beschreibung Haus sdf sdfe"
android:textSize="17sp"
android:textStyle="bold"></TextView>
<ImageButton
android:id="#+id/main_list_rv_message_btn"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentRight="true"
android:backgroundTint="#color/white"
android:scaleType="centerCrop"
android:src="#drawable/send"></ImageButton>
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
I've reviewed your code and I think the problem is in the result_list_rv.xml file,
try to set the main linear layout width = match_parent and last RelativeLayout height = wrap_content

How to make Scrollview automatically scroll to the bottom when RadioButton is clicked

How to make Scrollview automatically scroll to the bottom when RadioButton is clicked
May I know How to make the Scroll view automatically scroll down to the next_button when any of the Radio Button is clicked ,
in the same time I need to call "setMeal() method from the ViewModel when the Radio Button is clicked.
<?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"
tools:context=".ui.MainMeal">
<data>
<variable
name="viewModel"
type="com.example.mymeal.model.OrderViewModel" />
<variable
name="mainMeal"
type="com.example.mymeal.ui.MainMeal" />
</data>
<ScrollView
android:layout_width="match_parent"
android:id="#+id/scrollView"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:paddingBottom="16dp">
<com.google.android.material.card.MaterialCardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
app:layout_constraintBottom_toTopOf="#+id/divider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioGroup
android:id="#+id/main_meal_options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/royal_lobster"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='#{viewModel.menuItems["royal butter lobster"].name}'
android:onClick='#{() -> viewModel.setMeal("royal butter lobster")}'
android:textAppearance="?attr/textAppearanceBody1"
tools:text="Royal Butter Lobster" />
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/royal_lobster_image"
android:layout_width="match_parent"
android:layout_height="194dp"
android:layout_margin="8dp"
app:shapeAppearanceOverlay="#style/cut_corner"
app:srcCompat="#drawable/royal_butter_lobster" />
<TextView
android:id="#+id/royal_lobster_description"
style="#style/Widget.MenuItem.TextView.Info"
android:text='#{viewModel.menuItems["royal butter lobster"].description}'
tools:text="Entree 3 description" />
<TextView
android:id="#+id/royal_lobster_price"
style="#style/Widget.MenuItem.TextView.Info"
android:paddingTop="8dp"
android:text='#{viewModel.menuItems["royal butter
lobster"].getFormattedPrice()}'
tools:text="$0.00" />
<View
style="#style/Widget.MyMeal.Divider"
android:layout_width="match_parent"
android:layout_height="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/royal_lobster_description" />
<RadioButton
android:id="#+id/kebbeh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='#{viewModel.menuItems["kebbeh"].name}'
android:onClick='#{() -> viewModel.setMeal("kebbeh")}'
android:textAppearance="?attr/textAppearanceBody1"
tools:text="Kebbeh" />
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/kebbeh_image"
android:layout_width="match_parent"
android:layout_height="194dp"
android:layout_margin="8dp"
app:shapeAppearanceOverlay="#style/cut_corner"
app:srcCompat="#drawable/kebbeh" />
<TextView
android:id="#+id/kebbeh_description"
style="#style/Widget.MenuItem.TextView.Info"
android:text='#{viewModel.menuItems["kebbeh"].description}'
tools:text="Entree 4 description" />
<TextView
android:id="#+id/kebbeh_price"
style="#style/Widget.MenuItem.TextView.Info"
android:paddingTop="8dp"
android:text='#{viewModel.menuItems["kebbeh"].getFormattedPrice()}'
tools:text="$0.00" />
<View
style="#style/Widget.MyMeal.Divider"
android:layout_width="match_parent"
android:layout_height="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/kebbeh_description" />
<RadioButton
android:id="#+id/shish_tawook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='#{viewModel.menuItems["shish tawook"].name}'
android:onClick='#{() -> viewModel.setMeal("shish tawook")}'
android:textAppearance="?attr/textAppearanceBody1"
tools:text="Shish Tawook" />
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/shish_tawook_image"
android:layout_width="match_parent"
android:layout_height="194dp"
android:layout_margin="8dp"
app:shapeAppearanceOverlay="#style/cut_corner"
app:srcCompat="#drawable/shish_tawook" />
<TextView
android:id="#+id/shish_tawook_description"
style="#style/Widget.MenuItem.TextView.Info"
android:text='#{viewModel.menuItems["shish tawook"].description}'
tools:text="Entree 4 description" />
<TextView
android:id="#+id/shish_tawook_price"
style="#style/Widget.MenuItem.TextView.Info"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:text='#{viewModel.menuItems["shish tawook"].getFormattedPrice()}'
tools:text="$0.00" />
</RadioGroup>
</com.google.android.material.card.MaterialCardView>
<View
android:id="#+id/divider"
style="#style/Widget.MyMeal.Divider"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/cardView" />
<TextView
android:id="#+id/subtotal"
style="#style/Widget.MyMeal.TextView.Subtotal"
android:text='#{#string/subtotal(viewModel.subtotal)}'
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/divider"
tools:text="Subtotal $5.00" />
<Button
android:id="#+id/next_button"
style="#style/Widget.Order.Button.Next"
android:onClick="#{()-> mainMeal.goToNextFragment()}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/cancel_button"
app:layout_constraintTop_toBottomOf="#id/subtotal" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</layout>
This is the fragment class file
package com.example.mymeal.ui
class MainMeal : Fragment() {
// Binding object instance corresponding to the fragment_main_meal.xml layout.
private var _binding: FragmentMainMealBinding? = null
private val binding get() = _binding!!
//Get instance of OrderViewModel
private val sharedViewModel: OrderViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMainMealBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = sharedViewModel
binding.mainMeal = this
}
//Navigate to the salad menu fragment
fun goToNextFragment() {
findNavController().navigate(R.id.action_mainMeal_to_saladMenu)
}
//Cancel the order
private fun cancelOrder() {
//Reset the values
sharedViewModel.resetOrder()
//Navigate back to the start fragment
findNavController().navigate(R.id.action_mainMeal_to_startFragment)
}
private fun doNothing() {
return
}
//confirmation before cancel the order
fun showDialog() {
MaterialAlertDialogBuilder(requireContext()).setMessage(getString(R.string.cancel_order))
.setCancelable(true)
.setNegativeButton(getString(R.string.yes)) { _, _ -> cancelOrder() }
.setPositiveButton(getString(R.string.no)) { _, _ -> doNothing() }.show()
}
/**
Clear out the binding object when the view hierarchy associated with the fragment
is being removed
*/
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Use the below code when the radio button is checked
scrollView.post(new Runnable() {
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
Try this:
fun scrollToViewBottom(scrollView: ScrollView, childView: View) {
val delay: Long = 500 //delay to let finish with possible modifications to ScrollView
scrollView.postDelayed({ scrollView.smoothScrollTo(0, childView.bottom) }, delay)
}
Call the function:
radioButton.setOnClickListener {
if (radioButton.isChecked) {
println("checked")
scrollToViewBottom(ScrollViewExplore, Mypage)
}
}

RecyclerView doesn't display all data

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

Fragment Layout is blank

I am passing an object (Contact) of type contacts, onclick in RecyclerView and displaying it in a Fragment in another activity using intents and Serialize. But the content is blank no fields displayed or titles.. blank layout not sure what the issue is here...
Calling the activity with fragment
holder.itemView.setOnClickListener {
val intent = Intent(context, ContactDetailsHome::class.java)
intent.putExtra("contact", contact as Serializable)
intent.putExtra("Edit", true)
context.startActivity(intent)
}
Fragment Contact Details where the layout is generated
class ContactDetails : Fragment() {
companion object {
#JvmStatic
fun start(context: Context, contact: Contact?, isEdit: Boolean) {
val starter = Intent(context, ContactDetails::class.java)
.putExtra("contact", contact as Serializable)
.putExtra("Edit", isEdit)
context.startActivity(starter)
}
}
private lateinit var contact: Contact
private lateinit var numEditList: ArrayList<EditText>
private lateinit var emailEditList: ArrayList<EditText>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
inflater.inflate(R.layout.fragment_view_contact_details, container, false)
numEditList = ArrayList()
emailEditList = ArrayList()
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
if (activity?.intent?.getBooleanExtra("Edit", false) == true){
initEdit()
}else{
initAdd()
}
delete_contact!!.setOnClickListener {
deleteContact()
Toast.makeText(activity, "Contact Deleted Successfully", Toast.LENGTH_SHORT).show()
activity?.finish()
}
}
private fun initEdit() {
//getting the value from the object
contact = (activity?.intent?.getSerializableExtra("contact") as Contact)
//assigning it to fields to be displayed
contDetails_name.setText(contact.name)
if (contact.numbers.isEmpty()) {
phoneTitle!!.visibility = View.GONE
}
if (contact.emails.isEmpty()) {
title_emails!!.visibility = View.GONE
}
for (number in contact.numbers) {
val editText = EditText(activity)
editText.setText(number)
editText.setTextColor(Color.parseColor("#0D0D0D"))
editText.typeface = Typeface.DEFAULT_BOLD
editText.textSize = 20f
editText.isEnabled = false
numEditList.add(editText)
contact_numbers_layout!!.addView(editText)
}
for (email in contact.emails) {
val editText = EditText(activity)
editText.setText(email)
editText.setTextColor(Color.parseColor("#0D0D0D"))
editText.typeface = Typeface.DEFAULT_BOLD
editText.textSize = 20f
editText.isEnabled = false
emailEditList.add(editText)
contact_emails_layout!!.addView(editText)
}
edit_contact!!.setOnClickListener {
if (contDetails_name.isEnabled) {
if (contDetails_name.text.toString().isEmpty()) {
Toast.makeText(activity, "Contact name can't be empty", Toast.LENGTH_SHORT)
.show()
}
contDetails_name.isEnabled = false
for (editText in numEditList) {
editText.isEnabled = false
}
for (editText in emailEditList) {
editText.isEnabled = false
}
deleteContact()
addContact()
edit_contact.text = "Edit"
Toast.makeText(activity, "Contact updated successfully", Toast.LENGTH_SHORT).show()
} else {
contDetails_name.isEnabled = true
for (editText in numEditList) {
editText.isEnabled = true
}
for (editText in emailEditList) {
editText.isEnabled = true
}
edit_contact.text = "Save"
}
}
}
layout file
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Contacts.ui.ContactDetails">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:padding="10dp"
app:cardCornerRadius="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="8dp"
android:text="Name"
android:textAllCaps="true"
android:textSize="16sp" />
<EditText
android:id="#+id/contDetails_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:enabled="false"
android:hint="Contact Name"
android:inputType="textPersonName"
android:textColor="#color/txtcolor"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/phoneTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_marginTop="8dp"
android:text="Phone/Mobile No:"
android:textAllCaps="true"
android:visibility="visible"
android:textSize="16sp" />
<LinearLayout
android:id="#+id/contact_numbers_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:orientation="vertical" />
<TextView
android:id="#+id/title_emails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_marginTop="8dp"
android:text="Email"
android:textAllCaps="true"
android:textSize="16sp" />
<LinearLayout
android:id="#+id/contact_emails_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:orientation="vertical" />
<Button
android:id="#+id/edit_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginTop="20dp"
android:background="#color/colorPrimary"
android:text="Edit"
android:textColor="#fff"
android:textSize="20sp" />
<Button
android:id="#+id/delete_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginTop="20dp"
android:background="#color/colorPrimary"
android:layout_marginBottom="8dp"
android:text="Delete"
android:textColor="#fff"
android:textSize="20sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
discovered that I didn't declare view during creation in oncreateView before returning it. resulting in no view being generated hence blank fragment.
Val view:View = ....
return view

Populate UI from a ViewModel in Kotlin

This is the first time I am using Android Architecture. I have decided to go with MVVM structure but I am stuck at the point where I have no idea how to set the textViews in my XML with the data I pull from the database.
Checking the logs, I have seen that the function calls to my database (Firestore) does retrieve the correct data documents. Do I set the UI elements from the Activity,ViewModel or the Fragment? (Please note that I'm using a Navigation bar and controller)
Please assist me, my code is as follows:
My Single Activity:
class HomeActivity : AppCompatActivity() {
// Create the three objects for the fragments
lateinit var homeFragment: HomeFragment
lateinit var visitsFragment: VisitsFragment
lateinit var profileFragment: ProfileFragment
// ViewModels
lateinit var customerViewModel: CustomerViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
// Initialize the bottom nav bar and navigation controller and then merge them
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.btm_nav)
val navigationController = findNavController(R.id.fragmentHost)
bottomNavigationView.setupWithNavController(navigationController)
// Create app bar config object so that you can rename the bar ontop with the tab name
val appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment,R.id.visitsFragment,R.id.profileFragment))
setupActionBarWithNavController(navigationController,appBarConfiguration)
// View Model
customerViewModel = ViewModelProvider(this).get(CustomerViewModel::class.java)
customerViewModel.retrieveCustomer().observe(this, Observer { it })
}
// This function creates the menu object by inflating it with the resource we gave it (menu resource).
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main,menu);
return true
}
// This function checks which menu item was selected and performs the task associated with the item selected.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId;
// If Log Out menu item was selected
if (id == R.id.menuLogOut){
// Sign the user out
FirebaseAuth.getInstance().signOut()
// Finish this activity
finish()
// Start the initial activity
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
// Display the message to the user
Toast.makeText(this, "Successfully Signed Out", Toast.LENGTH_SHORT).show()
return true
}
return super.onOptionsItemSelected(item)
}
}
My View Model:
class CustomerViewModel: ViewModel() {
val TAG = "CustomerViewModel"
var db = Firebase.firestore
var user = FirebaseAuth.getInstance().currentUser
var liveData = MutableLiveData<List<Customer>>()
var cusArray = arrayListOf<Customer>()
var docRef = user?.uid
fun retrieveCustomer(): MutableLiveData<List<Customer>>
{
db.collection("users").document(docRef.toString())
.get()
.addOnSuccessListener { document ->
if (document != null)
{
val data = document
// Set the data
val name = data.get("name") as String
val surname = data.get("surname") as String
val email = data.get("email") as String
val contactNo = data.get("contact no") as String
val customer = Customer(name, surname, email, contactNo)
cusArray.add(customer)
liveData.value = cusArray
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
}
else
{
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with " + exception.message, exception)
}
return liveData
}
}
My Object Class
package com.CleanWheels.cleanwheels.DataClasses
data class Customer(
val name: String?,
val surname: String?,
val email: String?,
val contactNo: String?
)
My XML file (profile_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="match_parent"
tools:context=".Fragments.ProfileFragment">
<TextView
android:id="#+id/banner"
android:layout_width="499dp"
android:layout_height="290dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="-6dp"
android:layout_marginTop="0dp"
android:layout_marginEnd="0dp"
android:background="#color/colorPrimary"
android:layout_marginLeft="-6dp"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_marginRight="0dp" />
<ImageView
android:id="#+id/image"
android:layout_width="154dp"
android:layout_height="159dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="53dp"
android:layout_marginEnd="132dp"
android:layout_marginRight="132dp"
android:layout_marginBottom="78dp"
android:src="#drawable/ic_action_profile" />
<LinearLayout
android:id="#+id/layout_1"
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_below="#id/banner"
android:layout_marginLeft="80dp"
android:layout_marginTop="100dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name:"
android:textSize="18sp"/>
<TextView
android:id="#+id/profileNameUI"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/layout_2"
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_below="#id/layout_1"
android:layout_marginLeft="80dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Surname:"
android:textSize="18sp"/>
<TextView
android:id="#+id/profileSurnameUI"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/layout_3"
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_below="#id/layout_2"
android:layout_marginLeft="80dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Email Address:"
android:textSize="18sp"/>
<TextView
android:id="#+id/profileEmailUI"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/layout_4"
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_below="#id/layout_3"
android:layout_marginLeft="80dp"
android:layout_marginBottom="50dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Contact No:"
android:textSize="18sp" />
<TextView
android:id="#+id/profileContactUI"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_5"
android:layout_width="65dp"
android:layout_height="220dp"
android:layout_below="#id/banner"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="90dp"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:src="#drawable/ic_action_profile_name_ui"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:src="#drawable/ic_action_profile_surname_ui"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:src="#drawable/ic_action_profile_email_ui"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="0dp"
android:layout_weight="1"
android:src="#drawable/ic_action_profile_contact_ui"/>
</LinearLayout>
The profile_fragment class file:
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ProfileFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ProfileFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
#JvmStatic
fun newInstance(param1: String, param2: String) =
ProfileFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
Then finally, the View I am trying to populate
You need to move all the logic to ProfileFragment once you navigate to ProfileFragment data will be set.
Example:
ProfileFragment
class ProfileFragment : Fragment() {
private val customerViewModel: CustomerViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_profile, container, false)
val name = view.findViewById<TextView>(R.id.name)
val surname = view.findViewById<TextView>(R.id.surname)
val email = view.findViewById<TextView>(R.id.email)
val contact = view.findViewById<TextView>(R.id.contact)
//calling initially here
customerViewModel.retrieveCustomer()
customerViewModel.liveData.observe(viewLifecycleOwner, Observer {
//customer index at 0
val customer = it[0]
name.text = customer.name
surname.text = customer.surname
email.text = customer.email
contact.text = customer.contactNo
})
return view
}
CustomerViewModel.kt
class CustomerViewModel(application: Application) : AndroidViewModel(application) {
var liveData = MutableLiveData<List<Customer>>()
fun retrieveCustomer(){
//Your logic to get data from Firebase or any remote or db
val listOfCustomer = mutableListOf<Customer>()
val customer = Customer("name", "surname","email", "contqct")
listOfCustomer.add(customer)
liveData.postValue(listOfCustomer)
}
}
fragment_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:padding="8dp"
android:textSize="24dp"
/>
<TextView
android:id="#+id/surname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Surname"
android:padding="8dp"
android:textSize="24dp"
/>
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:padding="8dp"
android:textSize="24dp"
/>
<TextView
android:id="#+id/contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:padding="8dp"
android:textSize="24dp"
/>
</LinearLayout>

Categories

Resources