Кнопка с кликом Kotlin в ListView

#android #kotlin #button #android-listview

#Android #kotlin #кнопка #android-listview

Вопрос:

Я создаю приложение для приготовления Котлина, и у меня есть список названий блюд с кнопкой для просмотра блюда, которое будет создаваться при добавлении нового блюда в виде списка. Предполагается, что кнопка перенаправляет пользователей к новому действию, в котором будет показан рецепт блюда. Однако кнопка не работает. Я попробовал несколько предложенных решений, но все равно не работает.

xml-файл списка:

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    tools:context=".ViewRecipe">

    <ListView
        android:id="@ id/recipeList"
        android:layout_width="367dp"
        android:layout_height="565dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@ id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="39dp"
        android:text="Recipe List"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  

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=".Recipes">

    <TextView
        android:id="@ id/recipeView2"
        android:layout_width="228dp"
        android:layout_height="28dp"
        android:layout_marginStart="23dp"
        android:layout_marginTop="47dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@ id/recipeDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_marginEnd="20dp"
        android:text="View"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
  

Файл Kotlin для просмотра списка:

 package com.example.recipeapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ListView
import com.google.firebase.database.*

class ViewRecipe : AppCompatActivity() {

    lateinit var ref: DatabaseReference
    lateinit var recipeList: MutableList<AddRecipeModelClass>
    lateinit var listView: ListView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_recipe)

        recipeList = mutableListOf()
        ref = FirebaseDatabase.getInstance().getReference("addRecipes")
        listView = findViewById(R.id.recipeList)

        ref.addValueEventListener(object: ValueEventListener {
            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }

            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    recipeList.clear()
                    for(h in snapshot.children){
                        val recipe = h.getValue(AddRecipeModelClass::class.java)
                        recipeList.add(recipe!!)
                    }

                    val adapter = RecipeAdapter(applicationContext, R.layout.activity_recipes, recipeList)
                    listView.adapter = adapter
                }
            }

        });
    }
}
  

Файл Kotlin для кнопки:

 package com.example.recipeapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class Recipes : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recipes)

        val navView = findViewById<Button>(R.id.recipeDetails)
        navView.setOnClickListener{
            val intent = Intent(this, RecipeDetails::class.java)
            startActivity(intent)
        }
    }
}
  

RecipeAdapter.kt

 package com.example.recipeapp

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView

class RecipeAdapter(val mCtx: Context, val layoutResId: Int, val recipeList: List<AddRecipeModelClass>)

    : ArrayAdapter<AddRecipeModelClass>(mCtx, layoutResId, recipeList) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val layoutInflater: LayoutInflater = LayoutInflater.from(mCtx)
        val view: View = layoutInflater.inflate(layoutResId, null)

        val recipeView = view.findViewById<TextView>(R.id.recipeView2)

        val recipe = recipeList[position]

        recipeView.text = recipe.dishName

        return view
    }
}
  

Редактировать:

Я обнаружил, что проблема возникает из-за того, что кнопка «просмотр» находится внутри представления списка. Я попытался использовать «кнопку», расположенную вне listview, и она работает просто отлично. Я не могу решить ее, используя решения, найденные в Интернете.

На изображении показаны 2 типа кнопок. Вид находится внутри listview, кнопка — вне listview. Изображение для лучшего понимания

Любая помощь будет принята с благодарностью.

Комментарии:

1. Можете ли вы публиковать журналы ошибок?

2. Я не вижу никаких отображаемых ошибок, просто ничего не происходит, когда я нажимаю кнопку

3. можете ли вы опубликовать код для класса адаптера

4. @Sharvin решает ли мой ответ вашу проблему? Вы все еще сталкиваетесь с той же проблемой?

5. @LakhwinderSingh я добавил ее.

Ответ №1:

Я не прочитал весь ваш код, но одна проблема, которую я обнаружил, заключается в следующем:

 navView.setOnClickListener{
       val intent = Intent(this, RecipeDetails::class.java)
       //                  ^^^^
       startActivity(intent)
}
  

this В этой области относится к View.OnClickListener объекту, переданному setOnclickListener функции. Не для контекста приложения.

Из документов kotlin :

Чтобы получить доступ к этому из внешней области (класс, или функция расширения, или помеченный литерал функции с получателем), мы пишем @label, где @label — это метка в области, из которой это должно быть

Итак, вы должны делать это вместо этого:

 navView.setOnClickListener{
       val intent = Intent(this@Recipes, RecipeDetails::class.java)
       //                    ^^^^ note the label @Recipes
       startActivity(intent)
}
  

В качестве альтернативы вы можете вызвать Intent конструктор извне объекта View.OnClickListener , в onCreate функции:

 val intent = Intent(this, RecipeDetails::class.java)
val navView = findViewById<Button>(R.id.recipeDetails)

navView.setOnClickListener{
       startActivity(intent)
}
  

Комментарии:

1. Я попробовал оба предложенных метода и все еще сталкиваюсь с той же проблемой

Ответ №2:

Поместите это в свой класс activity и убедитесь, что AddRecipeModelClass доступен для отправки

 private val onItemAction: (AddRecipeModelClass) -> Unit = { it ->
val intent = Intent(this@ViewRecipe , RecipeDetails::class.java)
intent.putExtra("recipe", it)
startActivity(intent)
}
  

получить рецепт из намерения в новом действии

Добавьте прослушиватель кликов в ваши адаптеры getView

 class RecipeAdapter(val mCtx: Context, val layoutResId: Int,
       val recipeList: List<AddRecipeModelClass>,private val onItemSelected: (AddRecipeModelClass) -> Unit?)
        : ArrayAdapter<AddRecipeModelClass>(mCtx, layoutResId, recipeList) {  
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val layoutInflater: LayoutInflater = LayoutInflater.from(mCtx)
            val view: View = layoutInflater.inflate(layoutResId, null)   
            val recipeView = view.findViewById<TextView>(R.id.recipeView2)
            val btn= findViewById<Button>(R.id.recipeDetails)                 
            val recipe = recipeList[position]
            btn.setOnClickListener{
                onItemSelected(recipe)
            } 
            recipeView.text = recipe.dishName    
            return view
        }
    }
  

добавить функцию в конструктор

  val adapter = RecipeAdapter(applicationContext, R.layout.activity_recipes, recipeList,onItemAction)