How to setOnItemClickListener for List View with custom adapter by Kotlin

I use custom adapter for List View on my android app . I do not know how can set the listener for the item click. I use Kotlin for my app.

This is my adapter layout.

<?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">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <CheckBox
        android:id="@+id/cbx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <TextView
        android:id="@+id/txtNameNote"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_toRightOf="@+id/cbx"
        />
    <TextView
        android:id="@+id/txtPercent"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="TextView"
        android:layout_toRightOf="@+id/cbx"
        android:layout_below="@+id/txtNameNote"
        />
    </RelativeLayout>
</LinearLayout>
This is my adapter code

class CustomAdapter(internal var context: Context, resource: Int, internal var listNote: ArrayList<Note>) : ArrayAdapter<Note>(context, resource, listNote) {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        // TODO Auto-generated method stub
        val inflater = (context as Activity).layoutInflater
        convertView = inflater.inflate(R.layout.rowlistitem, parent, false)
        val name = convertView!!.findViewById<View>(R.id.txtNameNote) as TextView
        val percent = convertView.findViewById<View>(R.id.txtPercent) as TextView
        val cb = convertView.findViewById<View>(R.id.cbx) as CheckBox
        name.text = listNote[position].name
        percent.text = "Percent: " + listNote[position].percent + "%"

        if (listNote[position].status == NoteStatus.Active.value)
            cb.isChecked = false
         else{
            name.paintFlags = (name.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG)
            cb.isChecked = true
        }
       }
      }
        return convertView
    }
}

Some one can help me out ?

Upvotes: 1

Views: 2223

Answers (2)

LiberatorBuddy
LiberatorBuddy

Reputation: 1

The following code is used for making a quiz application using list view

Custom Adapter code

package com.example.myapplication

import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore.Audio.Radio
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import org.w3c.dom.Text
import java.lang.Exception

data class  QuizOption(
    val optionText: String,
    val isCorrect: Boolean
)

data class Question(
    val questionText: String,
    val options: List<QuizOption>,
)

class QuestionAdapter(private val context: Context, public  val questions: List<Question>) : BaseAdapter() {
    override fun getCount(): Int {
        return  questions.size
    }

    override fun getItem(p0: Int): Any {
        return  questions[p0]
    }

    override fun getItemId(p0: Int): Long {
        return  p0.toLong()
    }

    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
        val view = p1 ?: LayoutInflater.from(context).inflate(R.layout.quiz_list, p2, false)
        val question = questions[p0]

        val questionText = view.findViewById<TextView>(R.id.question)
        val option1RadioButton = view.findViewById<RadioButton>(R.id.opt1);
        val option2RadioButton = view.findViewById<RadioButton>(R.id.opt2);
        val option3RadioButton = view.findViewById<RadioButton>(R.id.opt3);
        val option4RadioButton = view.findViewById<RadioButton>(R.id.opt4);

        questionText.text = question.questionText
        option1RadioButton.text = question.options[0].optionText
        option2RadioButton.text = question.options[1].optionText
        option3RadioButton.text = question.options[2].optionText
        option4RadioButton.text = question.options[3].optionText

        option1RadioButton.tag = question.options[0].isCorrect
        option2RadioButton.tag = question.options[1].isCorrect
        option3RadioButton.tag = question.options[2].isCorrect
        option4RadioButton.tag = question.options[3].isCorrect

        return  view
    }
}

Rest of the main code

class QuizPage : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_quiz_page)
    val name = intent.getStringExtra("Name")
    val nameView = findViewById<TextView>(R.id.nameView)
    nameView.text = "Hello $name!"
    val questions = listOf<Question>(Question("Question 1", listOf(QuizOption("Option 1", true),QuizOption("Option 2", false),QuizOption("Option 3", false),QuizOption("Option 4", false))),Question("Question 2", listOf(QuizOption("Option 1", false),QuizOption("Option 2", true),QuizOption("Option 3", false),QuizOption("Option 4", false))),Question("Question 3", listOf(QuizOption("Option 1", false),QuizOption("Option 2", false),QuizOption("Option 3", true),QuizOption("Option 4", false))))
    val listView = findViewById<ListView>(R.id.listView)
    val adapter = QuestionAdapter(this, questions)
    listView.adapter = adapter
    val button = findViewById<Button>(R.id.button2)
    button.setOnClickListener{
        val alertDialogBuilder = AlertDialog.Builder(this)
        alertDialogBuilder.setTitle("Confirm Submission!")
        alertDialogBuilder.setMessage("Are you sure that you want to submit your answers?")
        alertDialogBuilder.setPositiveButton("Yes") { _, _, ->
            var totalScore = 0
            for (i in 0 until 4) {
                val radioGroup = listView.getChildAt(i)?.findViewById<RadioGroup>(R.id.radioGroup)
                if (radioGroup != null) {
                    val selectedRadioButtonId = radioGroup.checkedRadioButtonId
                    if (selectedRadioButtonId != -1) {
                        val radioButton = radioGroup.findViewById<RadioButton>(selectedRadioButtonId)
                        val isCorrect = radioButton.tag as Boolean
                        Toast.makeText(this, "question $i correct ${radioButton.tag}", Toast.LENGTH_SHORT).show()
                        if(isCorrect){
                            totalScore += 10
                        }
                        else{
                            totalScore -=5
                        }
                    }
                }
            }
            if(totalScore>10){
                val cL = findViewById<ConstraintLayout>(R.id.cL)
                cL.setBackgroundColor(Color.parseColor("#00FF00"))
            }
//                button.visibility = View.GONE
                Toast.makeText(this, "Total Score: $totalScore", Toast.LENGTH_LONG).show()
                val intent = Intent(this, alarm::class.java)
                intent.putExtra("Score", totalScore)
                startActivity(intent)
            }
            alertDialogBuilder.setNegativeButton("Cancel"){_, _, ->
                Toast.makeText(this, "No", Toast.LENGTH_LONG).show()
            }
            alertDialogBuilder.show();
        }
    }
}

Code for listview on click listener

package com.example.listview;

import

public class MainActivity extends AppCompatActivity {

ListView listView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

listView=findViewById(R.id.listview);

String[]text={"Java", "Ruby", "python", "Swift", "PHp", "c", "C++"};

ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(context: this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, text); listView.setAdapter(arrayAdapter);

ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> adapterView, View view, int i, long 1) {

switch (1){

case 0:

Toast.makeText(context: MainActivity.this, text: "java", Toast.LENGTH_SHORT).show();

break;

case 1:

Toast.makeText( context: MainActivity.this, text: "java", Toast.LENGTH_SHORT).show();

break;

case 2:

Toast.makeText(context: MainActivity.this, text: "java", Toast.LENGTH_SHORT).show();

break;

case 3:

Toast.makeText(context: MainActivity.this, Text: "java", Toast.LENGTH_SHORT).show();

Upvotes: 0

Emanuel
Emanuel

Reputation: 8106

The proper way in Kotlin is by creating a callback. Then you create a click listener in your Adapter and forward the result to your callback.

class CustomAdapter(
      internal var context: Context, 
      resource: Int, 
      internal var listNote: ArrayList<Note>,
      val callback: (Note) -> Unit) : ArrayAdapter<Note>(context, resource, listNote) {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        // .. do your bindings whatever 
        convertView.yourRootLayoutElement.setOnClickListener{ 
           if (callback != null) callback(listNote[position])
        }
        return convertView
    }
}

In your View where you create your adapter

CustomAdapter(...., { info { "Clicked $it" } })

I've not tested it since I don't use ListView. I recommend you to use RecyclerView. ListView is deprecated and not recommended for several reasons. Read some of the reasons here.

Edit: There is absolutely no reason for using a ListView over a RecyclerView. Even if it works, you should not use it. Learn the RecyclerView since ListView should no longer used.

Upvotes: 2

Related Questions