This question already has answers here:
Why do I get "unresolved reference" error for my view's name/ID when I type it in Kotlin?
(2 answers)
Closed 1 year ago.
when I try to use a TextView in my activity_main.xml, I get a “Unresolved reference” in my MainActivity.kt (even before try building)? I just can’t see what I’m doing wrong!
I've highlighted the error at the end of the MainActivity.
Any help appreciated.
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
val list = ArrayList<DataModel>()
list.add(DataModel(R.drawable.ad_astra, "Adastra"))
list.add(DataModel(R.drawable.beach_bum, "Beach Bum"))
list.add(DataModel(R.drawable.dark_phoenix, "Dark Phoenix"))
list.add(DataModel(R.drawable.glass, "Glass"))
val adapter = DataAdapter(list)
carouselRecyclerview.adapter = adapter
carouselRecyclerview.set3DItem(true)
carouselRecyclerview.setAlpha(true)
val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
val currentlyCenterPosition = carouselRecyclerview.getSelectedPosition()
carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
override fun onItemSelected(position: Int) {
//Cente item
Toast.makeText(this#MainActivity, list[position].text, Toast.LENGTH_LONG).show()
ShowMeIt.text = "Why does cause a Unresolved reference?"
ShowMeIt.text = list[position].text
}})
}
}
activity_main.xml
<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=".MainActivity">
<com.jackandphantom.carouselrecyclerview.CarouselRecyclerview
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler"/>
<TextView
android:id="#+id/ShowMeIt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="186dp"
android:layout_marginRight="186dp"
android:layout_marginBottom="106dp"
android:text="Hello" />
</RelativeLayout>
I think you need to define on MainActivity.kt like this
val ShowMeIt= findViewById<TextView>(R.id.ShowMeIt)
Related
everyone. I suddenly get an Unresolved reference error displayed in my layouts in RecyclerView. I've already restarted Android Studio, rebuilt and cleaned the project. All without success.
AddNewHomeFragment.kt:
class AddNewHomeFragment : Fragment() {
listImg = ArrayList()
var rv_img:RecyclerView = view.findViewById(R.id.recyclerViewImgs)
rv_img.layoutManager = GridLayoutManager(requireContext(),3)
adapter = CustomerAdapter(requireContext(),listImg){
var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,IMAGE_REQUEST)
}
rv_img.adapter = adapter
...
}
My CustomAdapter for RecyclerView:
class CustomerAdapter(val context: Context,
private val listImg:ArrayList<Int>, private val onClickFunction: ((Any?) -> Unit)? = null):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>() {
class MyCustomViewHolder(view: View):RecyclerView.ViewHolder(view) {
//Unresolved reference: customImg
val customImg:ImageView = view.findViewById(R.id.customImg)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCustomViewHolder {
//Unresolved reference: single_img
val inflate = LayoutInflater.from(context).inflate(R.layout.single_img,parent,false)
return MyCustomViewHolder(inflate)
}
override fun onBindViewHolder(holder: MyCustomViewHolder, position: Int) {
holder.customImg.setImageResource(listImg[position])
holder.customImg.setOnClickListener {
this#CustomerAdapter.onClickFunction?.invoke(listImg[position])
}
}
override fun getItemCount(): Int {
return listImg.size
}
}
fragment_add_new_home.xml:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewImgs"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.recyclerview.widget.RecyclerView>
single_img.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_marginEnd="5dp"
android:layout_marginBottom="8dp"
android:background="#drawable/layout_for_imgs"
android:id="#+id/customImg"
app:layout_constraintDimensionRatio="1"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:src="#drawable/ic_baseline_add_home_24">
</ImageView>
</androidx.constraintlayout.widget.ConstraintLayout>
I made a dialogue box and I put radio group in it and I add three radio button 1)male 2)female 3)others if user select male so the selected radio button male should be shown in text View
Here, I would like to share you here a simple app with both the activity and layout code. I hope this will help you.
First the layout
<?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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="100dp"
tools:context=".TestActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="What is your gender?"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtViewGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="-- Selected Gender --"
android:textSize="16sp" />
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select" />
</LinearLayout>
Second the Main Activity code
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class GenderActivity: AppCompatActivity() {
private lateinit var selectedGender: String
private var selectedGenderIndex: Int = 0
private val gender = arrayOf("Male", "Female", "Others")
private lateinit var txtViewGender: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test4)
txtViewGender = findViewById<TextView>(R.id.txtViewGender)
var androidButton: Button = findViewById<Button>(R.id.button)
androidButton.setOnClickListener {
showRadioDialog()
}
}
private fun showRadioDialog() {
selectedGender = gender[selectedGenderIndex]
MaterialAlertDialogBuilder(this)
.setTitle("Select your gender")
.setSingleChoiceItems(gender, selectedGenderIndex) { dialog, which ->
selectedGenderIndex = which
selectedGender = gender[which]
}
.setPositiveButton("Ok") { dialog, which ->
Toast.makeText(this, "Selected --> $selectedGender ", Toast.LENGTH_SHORT)
.show()
txtViewGender.text = selectedGender
}
.setNegativeButton("Cancel") { dialog, which ->
dialog.dismiss()
}
.show()
}
}
When you run the code, you will get the following two screens.
Screen 1
Screen 2
I am using a horizontal RecyclerView and showing images using the CircleImageView widget (See image below).
I am really struggling on how to make the list of items loop around, so that if you are in the last item, you will move to the first item in the list?
I have tried quite a few similar examples but I can’t make them work as they are in Java, or are quite complex. following is my code
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var adapter: ConcatAdapter
lateinit var userVerticalAdapter: UsersAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupDataInRecyclerView()
}
private fun setupDataInRecyclerView() {
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
userVerticalAdapter = UsersAdapter(DataSource.getUser())
val listOfAdapters = listOf(userVerticalAdapter)
adapter = ConcatAdapter(listOfAdapters)
recyclerView.adapter = adapter
}
}
Adapter.kt
class UsersAdapter(
private val users: ArrayList<User>
) : RecyclerView.Adapter<UsersAdapter.DataViewHolder>() {
class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(user: User) {
itemView.textViewUserName.text = user.name
Glide.with(itemView.imageViewAvatar.context)
.load(user.avatar)
.into(itemView.imageViewAvatar)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
DataViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_layout, parent,false))
override fun getItemCount(): Int = users.size
override fun onBindViewHolder(holder: DataViewHolder, position: Int) =
holder.bind(users[position])
}
}
DataSource.kt
object DataSource {
fun getUser() = ArrayList<User>().apply {
add(User(1, "Chillis", R.drawable.chilli))
add(User(2, "Tomato", R.drawable.tomatoe))
add(User(3, "Sweetcorn", R.drawable.sweeetcorn))
add(User(4, "Potatoe", R.drawable.potatoe))
add(User(5, "Aubergine", R.drawable.aubmain))
add(User(12, "Onion", R.drawable.onion))
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/item_layout_banner"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="1dp">
<androidx.cardview.widget.CardView
android:layout_width="120dp"
android:layout_height="120dp"
app:cardCornerRadius="4dp"
app:cardMaxElevation="2dp"
app:cardElevation="1dp"
android:layout_centerInParent="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_centerHorizontal="true"
app:civ_border_width= "3dp"
app:civ_border_color= "#color/colorPrimary"
android:id="#+id/imageViewAvatar"
android:src="#drawable/ic_launcher_background"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Veg"
android:layout_below="#+id/imageViewAvatar"
android:id="#+id/textViewUserName"
android:gravity="center"
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:textColor="#000"
android:layout_marginBottom="5dp"
android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="8sp"
android:autoSizeMaxTextSize="15sp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
To achieve this first you have to override the getItemCount function of UsersAdapter to return a very large value such as Int.MAX_VALUE
// This enables your adapter to scroll past the actual list size
override fun getItemCount(): Int = Int.MAX_VALUE
Now change your onBindViewHolder to calculate actual position
// Lets say your list had 100 items
override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
// position can be larger than 100 (ex 101), because our getItemCount doesn't return actual list size
// so if we receive position as 101, which item should we display?
// that should be item 1. (for 102 -> 2, 201 -> 1) and so on
// this suggests use of modules
val pos = position % users.size
holder.bind(users[pos]) // bind the actual item
}
Now in your MainActivity after recyclerView.adapter = adapter line, add following line
// When RV is loaded scroll it to middle, so that user doesn't hit limit on both ends(easily)
rv.scrollToPosition(Int.MAX_VALUE/2)
I try to get a reference to an EditText in an object.
The import import kotlinx.android.synthetic.main.dialog_save_recording.dialog_save_recording_edittext_name doesn't work in the object.
My code:
object Dialog {
fun createDialog(context: Context, layoutId: Int? = null) {
val builder = AlertDialog.Builder(context)
if (layoutId != null) {
builder.setView(layoutId)
builder.setPositiveButton(context.getString(R.string.dialog_save_button_text)) { _, _ ->
//get the input of the editText here
}
... //not important for my question
The layout I want to reference:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:padding="#dimen/dialog_padding"
android:layout_margin="#dimen/dialog_margin">
<TextView
android:id="#+id/dialog_save_recording_textview_name"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/dialog_save_recording_name"
android:textSize="#dimen/text_size_normal" />
<EditText
android:id="#+id/dialog_save_recording_edittext_name"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/dialog_save_recording_name_hint"
android:importantForAutofill="no"
android:inputType="text"/>
</LinearLayout>
I tried it with findViewById or working with the layoutId but had no success for now. I'm searching for a solution without inherit the object from Activity().
Anyone an idea how to do this?
You first need to build the dialog:
val dialog = builder.build()
Then you can use:
val editText = dialog.requireViewById(R.id.dialog_save_recording_edittext_name)
After you apply changes, don't forget to display the dialog:
dialog.show()
am new in kotlin, i am just now making my first code app
there are 2 inputs & 1 button on which i set onclick sum
(i just drag & drop 2 inputs & 1 button, Don't have much knowledge because i have just started kotlin)
Mainactivity.kt
package com.example.hello
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun sum (view: View){
var a = number1.toString().toInt()
var b = number2.toString().toInt()
var result = a + b
textView2.text="Result: $result"
}
}
problem is when i click on sum button, my app automatically shuts down
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/number1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
tools:context=".MainActivity"
tools:layout_editor_absoluteX="-82dp"
tools:layout_editor_absoluteY="-24dp">
<Button
android:id="#+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginBottom="24dp"
android:hint="+"
android:onClick="sum"
app:layout_constraintBottom_toTopOf="#+id/number2"
app:layout_constraintStart_toStartOf="#+id/number2"
app:layout_constraintTop_toBottomOf="#+id/number1" />
<TextView
android:id="#+id/textView2"
android:layout_width="202dp"
android:layout_height="0dp"
android:layout_marginBottom="281dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/number2" />
<EditText
android:id="#+id/number2"
android:layout_width="254dp"
android:layout_height="0dp"
android:layout_marginEnd="61dp"
android:layout_marginBottom="96dp"
android:ems="10"
android:inputType="number"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/sum" />
<EditText
android:id="#+id/number1"
android:layout_width="269dp"
android:layout_height="0dp"
android:layout_marginTop="88dp"
android:layout_marginEnd="46dp"
android:layout_marginBottom="52dp"
android:ems="10"
android:inputType="number"
app:layout_constraintBottom_toTopOf="#+id/sum"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
am getting this error in debugs section:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hello, PID: 23117
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
As the comment said, it's hard to see what is wrong but I guess that number1 and number2 are views/EditTexts? in that case toString won't give you the text of those but instead a description of the object which for example could look like this:
"EditText:{ someinfo, 40183}"
And when you call toInt() on that String, kotlin doesn't know how to convert it and your app crashes.
Instead (if number1 and number2 are edittexts)
try:
number1.getText().toInt()
My guess is it's a NumberFormatException.
Solution:
fun sum (view: View){
var a = number1.text.toString().toInt()
var b = number2.text.toString().toInt()
var result = a + b
textView2.text="Result: $result"
}
You need to call text first to get the actual value in the input View. Calling toString on number1 and number2 will give you the string representation of these objects which is most likely a short description of the object and most likely not a number, hence, the NumberFormatException.