Kotlin WebView refresh button - kotlin

i googled a bit how to make a refresh button but i didn't really figured out how to make it. I already have the button in my activity_main but nothing in my MainActivity.kt yet. So my problem is now the function of the button to refresh the page again.
This is my Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:text="REFRESH"
android:id="#+id/button"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
And this is my MainActivity.kt
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
class MainActivity : AppCompatActivity() {
private lateinit var webView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.webview)
webView.settings.setJavaScriptEnabled(true)
webView.setInitialScale(1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (url != null) {
view?.loadUrl(url)
}
return true
}
}
webView.loadUrl("example.com")
}
}

You can try adding this:
findViewById<Button>(R.id.button).setOnClickListener {
webView.reload()
}

Related

How to implement onClick listener on nested recyclerview

I am trying to implement a click listener on a nested recyclerview so that when an item on the child recycler view is clicked, an action is performed. I can do it for the parent recyclerview, but can't seem to do it for child recyclerview items. I really appreciate you time and assistance on this.
Below is my MainActivity.kt
package com.example.nestedrecyclerview
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class ParentAdapter(private val parentList: List<ParentItem>,
private val listener : OnItemClickListener ) :
RecyclerView.Adapter<ParentAdapter.ParentViewHolder>() {
inner class ParentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val logoIv: ImageView = itemView.findViewById(R.id.parentLogoIv)
val titleTv: TextView = itemView.findViewById(R.id.parentTitleTv)
val childRecyclerView: RecyclerView = itemView.findViewById(R.id.ch)
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val position : Int = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
interface OnItemClickListener{
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ParentViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.parent_item, parent, false)
return ParentViewHolder(view)
}
override fun onBindViewHolder(holder: ParentViewHolder, position: Int) {
val parentItem = parentList[position]
holder.logoIv.setImageResource(parentItem.logo)
holder.titleTv.text = parentItem.title
holder.childRecyclerView.setHasFixedSize(true)
holder.childRecyclerView.layoutManager = GridLayoutManager(holder.itemView.context, 3)
val adapter = ChildAdapter(parentItem.mList)
holder.childRecyclerView.adapter = adapter
}
override fun getItemCount(): Int {
return parentList.size
}
}
======================================================
Below is ParentAdapter.kt
class ParentAdapter(private val parentList: List<ParentItem>,
private val listener : OnItemClickListener ) :
RecyclerView.Adapter<ParentAdapter.ParentViewHolder>() {
inner class ParentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val logoIv: ImageView = itemView.findViewById(R.id.parentLogoIv)
val titleTv: TextView = itemView.findViewById(R.id.parentTitleTv)
val childRecyclerView: RecyclerView = itemView.findViewById(R.id.ch)
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val position : Int = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
interface OnItemClickListener{
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ParentViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.parent_item, parent, false)
return ParentViewHolder(view)
}
override fun onBindViewHolder(holder: ParentViewHolder, position: Int) {
val parentItem = parentList[position]
holder.logoIv.setImageResource(parentItem.logo)
holder.titleTv.text = parentItem.title
holder.childRecyclerView.setHasFixedSize(true)
holder.childRecyclerView.layoutManager = GridLayoutManager(holder.itemView.context, 3)
val adapter = ChildAdapter(parentItem.mList)
holder.childRecyclerView.adapter = adapter
}
override fun getItemCount(): Int {
return parentList.size
}
}
====================================================
Below is ChildAdapter.kt
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ChildAdapter(private val childList: List<ChildItem>,
private val listener : OnItemClickListener) :
RecyclerView.Adapter<ChildAdapter.ChildViewHolder>() {
inner class ChildViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener{
val logo: ImageView = itemView.findViewById(R.id.childLogoIv)
val title: TextView = itemView.findViewById(R.id.childTitleTv)
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION)
listener.onChildItemClick(position)
}
}
interface OnItemClickListener {
fun onChildItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.child_item, parent, false)
return ChildViewHolder(view)
}
override fun onBindViewHolder(holder: ChildViewHolder, position: Int) {
holder.logo.setImageResource(childList[position].logo)
holder.title.text = childList[position].title
}
override fun getItemCount(): Int {
return childList.size
}
}
======================================
Below is parent_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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="8dp"
app:cardCornerRadius="8dp"
app:cardElevation="5dp"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="30dp"
android:layout_height="30dp"
app:cardCornerRadius="100dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/parentLogoIv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/parentTitleTv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="12dp"
android:text="Language"
android:textColor="#color/black"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/cardView"
app:layout_constraintStart_toEndOf="#id/cardView"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/childRecyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/constraintLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
=============================================================
Below is child_item.xml
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="5dp"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/childCardView"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="8dp"
app:cardCornerRadius="100dp"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/childLogoIv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/java" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/childTitleTv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginVertical="5dp"
android:text="Language"
android:textColor="#color/black"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#id/childCardView"
app:layout_constraintStart_toStartOf="#id/childCardView"
app:layout_constraintTop_toBottomOf="#+id/childCardView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
==================================================
Below is activity_main.xml
<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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/parentRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can set the tag on the View in onBindViewHolder, set the click listener to get the tag attribute and proceed to the next step of logic.
The following is an example of my writing: here I set the click event listener for the entire View.
package com.example.nestedrecyclerview
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlinx.stackoverflowtestapplication.R
class ParentAdapter(private val parentList: List<ParentItem>,
private val listener : OnItemClickListener ) :
RecyclerView.Adapter<ParentAdapter.ParentViewHolder>() {
inner class ParentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val logoIv: ImageView = itemView.findViewById(R.id.parentLogoIv)
val titleTv: TextView = itemView.findViewById(R.id.parentTitleTv)
val childRecyclerView: RecyclerView = itemView.findViewById(R.id.ch)
}
private val onClickListener: OnClickListener = OnClickListener {
if (it.tag is Int) {
val position = it.tag
TODO()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ParentViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.parent_item, parent, false)
view.setOnClickListener(onClickListener)
return ParentViewHolder(view)
}
override fun onBindViewHolder(holder: ParentViewHolder, position: Int) {
holder.itemView.tag = position
val parentItem = parentList[position]
holder.logoIv.setImageResource(parentItem.logo)
holder.titleTv.text = parentItem.title
holder.childRecyclerView.setHasFixedSize(true)
holder.childRecyclerView.layoutManager = GridLayoutManager(holder.itemView.context, 3)
val adapter = ChildAdapter(parentItem.mList)
holder.childRecyclerView.adapter = adapter
}
override fun getItemCount(): Int {
return parentList.size
}
}

The RecyclerView doesn't retrieve any data from Firebase and doesn't show any data

I just started working with Android Studio, and I've been trying to figure out what's wrong with this code for a few days now. When I run the program it shows nothing, and also there is no errors from Android Studio. I read the posts on the subject, but unfortunately I found nothing appropriate.
This is my activity class.
package ie.wit.donationx.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.database.*
import ie.wit.donationx.adapters.EventsAdapter
import ie.wit.donationx.databinding.ActivityEventsFeedBinding
import ie.wit.donationx.models.EventData
class EventsFeed : AppCompatActivity() {
lateinit var mDataBase: DatabaseReference
private lateinit var eventList:ArrayList<EventData>
private lateinit var mAdapter: EventsAdapter
private lateinit var binding: ActivityEventsFeedBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_events_feed)
binding = ActivityEventsFeedBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
eventList = ArrayList()
mAdapter = EventsAdapter(this,eventList)
var linearLayoutManager = LinearLayoutManager(this)
binding.recyclerEvents.layoutManager = linearLayoutManager
binding.recyclerEvents.setHasFixedSize(true)
binding.recyclerEvents.adapter = mAdapter
getEventsData()
}
private fun getEventsData() {
mDataBase = FirebaseDatabase.getInstance().getReference("Events")
mDataBase.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (eventSnapshot in snapshot.children) {
val event = eventSnapshot.getValue(EventData::class.java)
eventList.add(event!!)
}
binding.recyclerEvents.adapter = mAdapter
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
This is my Adapter
package ie.wit.donationx.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import ie.wit.donationx.R
import ie.wit.donationx.databinding.ItemListBinding
import ie.wit.donationx.models.EventData
class EventsAdapter(
var c: Context, var eventList: ArrayList<EventData>)
: RecyclerView.Adapter<EventsAdapter.EventViewHolder>() {
inner class EventViewHolder(var v: ItemListBinding): RecyclerView.ViewHolder(v.root){}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventViewHolder {
val infilter = LayoutInflater.from(parent.context)
val v = DataBindingUtil.inflate<ItemListBinding>(
infilter,R.layout.item_list,parent,
false
)
return EventViewHolder(v)
}
override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
val newList = eventList[position]
holder.v.isEvent = eventList[position]
holder.adapterPosition
}
override fun getItemCount(): Int {
return eventList.size
}
}
XML recyclerView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.EventsFeed">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/main_shapeable"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:background="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/main_search"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:ems="10"
android:hint="search"
android:inputType="textPersonName"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="#+id/main_shapeable"
app:layout_constraintEnd_toEndOf="#+id/main_shapeable"
app:layout_constraintStart_toStartOf="#+id/main_shapeable"
app:layout_constraintTop_toTopOf="#+id/main_shapeable" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerEvents"
tools:listitem="#layout/item_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_shapeable"/>
</androidx.constraintlayout.widget.ConstraintLayout>
XML file for items in recyclerView
<?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">
<data>
<variable
name="isEvent"
type="ie.wit.donationx.models.EventData" />
</data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="5dp"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_margin="10dp"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/eventImg"
android:imageUrl="#{isEvent.image}"
android:scaleType="centerCrop"
android:layout_width="140dp"
android:layout_height="140dp"/>
<LinearLayout
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/eventTitle"
android:textColor="#color/black"
android:textSize="20sp"
android:gravity="center"
android:textStyle="bold|normal"
android:layout_gravity="center"
android:text="#{isEvent.evenTitle}"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/eventInfo"
android:textColor="#android:color/darker_gray"
android:textSize="15sp"
android:gravity="center"
android:textStyle="bold|normal"
android:layout_gravity="center"
android:text="#{isEvent.info}"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
<View
android:background="#android:color/darker_gray"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</layout>
Data file
package ie.wit.donationx.models
class EventData {
var evenTitle: String? = null
var info: String? = null
var image: String? = null
constructor(){}
constructor(
evenTitle:String?,
info:String?,
image:String?
){
this.evenTitle = evenTitle
this.info = info
this.image = image
}
}
Firebase DB structure
When adding new list to the RecyclerView Adapter you need to call NotifyDataSetChanged()
Also, i advise to remove the list from the constructor of the adapter, and make a public function inside the adapter class that will update the private list created in the class.
private var items: MutableList<EventData> = mutableListOf()
fun setItems(newItemsList : List<EventData>){
eventList.clear()
eventList.addAll(newItemsList)
notifyDataSetChanged()
}
If you only update part of the list, you can create a separate function for that and use the more efficient notifyItemRangeInserted(), notifyItemInserted() or notifyItemChanged() \ notifyItemRangeChanged
You don't need to setAdaper again after getting EventsData
Just replace this line in getEventsData() :
binding.recyclerEvents.adapter = mAdapter
With :
if (eventList.size > 0) {
mAdapter.notifyDataSetChanged()
}
Edit:
You should not to add
android:imageUrl="#{isEvent.image}" in the ImageView,
you can use library to download the images from URL Like:
Picasso.
or
Fresco.
For Example using Picasso in your adapter:
override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
val newList = eventList[position]
holder.v.isEvent = eventList[position]
holder.adapterPosition
// here to download image for URL
Picasso.get().load(eventList[position].image)
.into(holder.v.eventImg)
}
Don't forget to add dependencies
implementation 'com.squareup.picasso:picasso:2.8'

why doesn't setText of TextView work in android studio in kotlin?

i discovered in android studio setText of TextView doesn't work. see next code. I expect if in nextCode append button is clicked, in textView text is changed to editText.text.toString(). but doesn't be changed. why so?
Activity.kt :
package com.example.myapplication
import android.content.Context
import android.content.Context.LAYOUT_INFLATER_SERVICE
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val editText = findViewById(R.id.editText) as EditText
val textView = findViewById(R.id.textView) as TextView
val button = findViewById(R.id.button) as Button
button.setOnClickListener(View.OnClickListener(){
#Override
fun onClick(view : View){
textView.setText(editText.text.toString())
}
})
}
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity"
android:orientation="vertical"
android:id="#+id/root_layout">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="append"
android:id="#+id/button"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:text="4"/>
</LinearLayout>
You are not setting up the click listener properly. Either specify
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
textView.setText(editText.text.toString())
}
})
or the lambda construction:
button.setOnClickListener {
textView.setText(editText.text.toString())
}

No adapter attached; skipping layout fragment Kotlin

This is my code and I can't see what is the problem. The error I keep seeing is No adapter attached; skipping layout.
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gsixacademy.android.bikesrevisited">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.BikesRevisited"
android:usesCleartextTraffic="true"
>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ADAPTER:
package com.gsixacademy.android.bikesrevisited.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gsixacademy.android.bikesrevisited.R
import com.gsixacademy.android.bikesrevisited.models.BikeModel
import com.gsixacademy.android.bikesrevisited.models.BikeResult
import kotlinx.android.synthetic.main.bikes_custom_row.view.*
class Adapter(
var bikeList: ArrayList<BikeResult>,
val bikesOnClickEvent:(BikesOnClickEvent)->Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.bikes_custom_row, parent, false)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
var myHolder = holder as MyViewHolder
myHolder.bindData(bikeList[position], position)
}
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindData(itemModel: BikeResult, position: Int) {
itemView.city_TV.text = itemModel.city
itemView.country_TV.text = itemModel.country
}
}
override fun getItemCount(): Int {
return bikeList.size
}
}
BIKES ON CLICK EVENT:
package com.gsixacademy.android.bikesrevisited.adapters
import com.gsixacademy.android.bikesrevisited.models.BikeResult
sealed class BikesOnClickEvent {
data class BikesClicked(val bike:BikeResult):BikesOnClickEvent()
}
APISERVICEBUILDER:
package com.gsixacademy.android.bikesrevisited.api
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiServiceBuilder {
val client=OkHttpClient.Builder().build()
val retrofit= Retrofit.Builder()
.baseUrl("http://api.citybik.es/v2/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
fun <T>buildService(service:Class<T>):T{
return retrofit.create(service)
}
}
BIKESAPI:
package com.gsixacademy.android.bikesrevisited.api
import com.gsixacademy.android.bikesrevisited.models.BikeModel
import retrofit2.Call
import retrofit2.http.GET
interface BikesApi {
#GET("networks")
fun getBikes(): Call<BikeModel>
}
BIKE MODEL
package com.gsixacademy.android.bikesrevisited.models
class BikeModel (val networks:ArrayList<BikeResult> )
BIKE RESULT
package com.gsixacademy.android.bikesrevisited.models
class BikeResult (
val city:String,val country:String
)
BIKE FRAGMENT
package com.gsixacademy.android.bikesrevisited
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.gsixacademy.android.bikesrevisited.R
import kotlinx.android.synthetic.main.recycler_view.*
import androidx.recyclerview.widget.LinearLayoutManager
import com.gsixacademy.android.bikesrevisited.adapters.Adapter
import com.gsixacademy.android.bikesrevisited.api.ApiServiceBuilder
import com.gsixacademy.android.bikesrevisited.api.BikesApi
import com.gsixacademy.android.bikesrevisited.models.BikeModel
import com.gsixacademy.android.bikesrevisited.models.BikeResult
import kotlinx.android.synthetic.main.recycler_view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class BikeFragment:Fragment() {
var request=ApiServiceBuilder.buildService(BikesApi::class.java)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view=inflater.inflate(R.layout.recycler_view,container,false)
val call=request.getBikes()
call.enqueue(object :Callback<BikeModel>{
override fun onResponse(call: Call<BikeModel>, response: Response<BikeModel>) {
if (response.isSuccessful){
var bikeResponse=response.body()
var bikeList=bikeResponse?.networks
if (bikeList!=null){
var bikelistAdapter=Adapter(bikeList){
}
recycler_view.layoutManager=LinearLayoutManager(context)
recycler_view.adapter=bikelistAdapter
}
}
else{}
}
override fun onFailure(call: Call<BikeModel>, t: Throwable) {
Toast.makeText(activity,t.message, Toast.LENGTH_SHORT)
.show()
}
})
return view
}
}
MAIN ACTIVITY:
package com.gsixacademy.android.bikesrevisited
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
SPLASH FRAGMENT:
package com.gsixacademy.android.bikesrevisited
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class SplashFragment:Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.splash,container,false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
GlobalScope.launch {
Thread.sleep(1500)
findNavController().navigate(R.id.action_splashFragment_to_bikeFragment)
}
}
}
layouts
activity_main
<?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=".MainActivity">
<fragment
android:id="#+id/navigation_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:navGraph="#navigation/navigation_graph"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
bikes_custom_row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:id="#+id/card_view_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="3dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
tools:ignore="UseCompoindDrawables">
<TextView
android:id="#+id/city_TV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="city"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/country_TV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="country"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
recycler_view
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view"/>
</androidx.constraintlayout.widget.ConstraintLayout>
splash
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background"
android:scaleType="centerInside"/>
</androidx.constraintlayout.widget.ConstraintLayout>
navigation_graph
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_graph"
app:startDestination="#id/splashFragment">
<fragment
android:id="#+id/splashFragment"
android:name="com.gsixacademy.android.bikesrevisited.SplashFragment"
android:label="SplashFragment" >
<action
android:id="#+id/action_splashFragment_to_bikeFragment"
app:destination="#id/bikeFragment"
app:popUpToInclusive="true" />
</fragment>
<fragment
android:id="#+id/bikeFragment"
android:name="com.gsixacademy.android.bikesrevisited.BikeFragment"
android:label="BikeFragment" />
</navigation>

How to find a view for Snackbar in fragment's onCreateView method if I use view binding and navigation component?

I'm trying to show a snack bar in fragment's onCreateView method but I don't know what view to passing inside the snack bar.
I'm very confused because I first time use the Navigation component and view binding and maybe is there a problem.
I tried binding.root but I got this exception:
java.lang.IllegalArgumentException: No suitable parent found from the
given view. Please provide a valid view.
After that I tried requireView().rootView as parameter but I also got this exception:
java.lang.IllegalStateException: Fragment XFragment{7a091b5}
(cefa1aef-59c3-4602-bcf1-b36f7d538cf9) id=0x7f0800f7} did not return a
View from onCreateView() or this was called before onCreateView()
MY CODE IN XFragment:
package com.sdsd.sds
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.google.android.material.snackbar.Snackbar
import com.sdsd.sds.databinding.FragmentXBinding
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class XFragment : Fragment() {
private var _binding: FragmenXBinding? = null
private val binding get() = _binding!!
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? {
_binding = FragmentXBinding.inflate(inflater, container, false)
binding.tvFgRegistration.setOnClickListener {
Navigation.findNavController(binding.root)
.navigate(R.id.action_f1_to_f2)
}
val snackbar: Snackbar = Snackbar.make(binding.root, "Succesful", Snackbar.LENGTH_LONG)
snackbar.show()
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
XFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
XML LAYOUT FILE:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic"
tools:context=".XFragment">
<EditText
android:id="#+id/etE"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:background="#color/translucent"
android:drawableStart="#drawable/ic_vector"
android:drawablePadding="5dp"
android:ems="10"
android:hint="#string/e_mail"
android:inputType="text"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<EditText
android:id="#+id/etP"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:background="#color/translucent"
android:drawableStart="#drawable/ic_vector"
android:drawablePadding="5dp"
android:ems="10"
android:hint="#string/password"
android:inputType="textPassword"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etE" />
<TextView
android:id="#+id/tvFgRegistration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="180dp"
android:layout_marginEnd="76dp"
android:layout_marginBottom="100dp"
android:text="#string/new_u"
android:textColor="#color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I only want to show a snack bar with a message when XFragment creates.
Can anyone tell me how to solve this and explain me in a few words why?
I found few ways to show a snack bar from a fragment
One of the solution is to use requireView().
Snackbar.make(
requireView(),
"Hello from Snackbar",
Snackbar.LENGTH_SHORT
).show()
This solution will work when you are inside any onClickListner{} you can simply pass it as a view and it will do the job.
binding.button.setOnClickListener {
Snackbar.make(
it,
"Hello from Snackbar",
Snackbar.LENGTH_SHORT
).show()
}
I found a simple solution and seems a Snackbar works excellent only with CoordinatorLayout as root layout so I set CoordinatorLayout as my root layout in the XML file.
In the Snackbar I just put binding.coordinatorlayout where coordinatorlayout is just an id of CoordinatorLayout in the XML file.
Code solution for a fragment is here:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentXBinding.inflate(inflater, container, false)
binding.tvFgRegistration.setOnClickListener {
Navigation.findNavController(binding.root)
.navigate(R.id.action_f1_to_f2)
}
val snackbar: Snackbar = Snackbar.make(binding.coordinatorlayout, "Succesful", Snackbar.LENGTH_LONG)
snackbar.show()
return binding.root
}
XML layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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/coordinatorlayout" //ID OF COORDINATOR LAYOUT
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic"
tools:context=".XFragment" >
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_backg">
<EditText
android:id="#+id/etE"
android:layout_width="0dp"
.
.
.
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
I faced the same issue while using navigation architecture.
What worked for me was
if(isAdded){
Snackbar.make(requireActivity.window.decorView.rootView,"message").show()
}