ListView不可点击(自定义适配器)

时间:2019-04-22 23:52:37

标签: android listview kotlin clickable

我正在尝试用Rome创建一个简单的RSS阅读器。

我的准系统实现使用ListView和我的自定义Adapter来填充feed_stub.xml。单击ListView项将启动另一个活动。

到目前为止,我有两个问题:

  1. 我的ListView项不可点击-我的setOnItemClickListener未触发。

  2. 如果我多次单击某些项目,则我的应用程序将崩溃并发生异常。这意味着我的适配器可能有错误。

ListView来自activity_main.xml

<ListView
            android:layout_width="0dp"
            android:layout_height="0dp" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/rssListView" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
            android:clickable="true" app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintVertical_bias="0.0"/>

我的MainActivity

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import cz.cvut.lenguduy.rss.Downloader
import cz.cvut.lenguduy.view.ViewHolder
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"

    private val downloader by lazy { Downloader(this, rssListView) }

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

        rssListView.setOnItemClickListener { parent, _, position, _ ->
            Log.d(TAG, "rssListView: item @pos $position clicked")
            val intent = Intent(this, SecondActivity::class.java)
            val item = parent.getItemAtPosition(position) as ViewHolder

            Toast.makeText(this, "clicked", Toast.LENGTH_LONG).show()

            intent.putExtra("title", item.tvName.text)
            intent.putExtra("text", item.tvSummary.text)
            this.startActivity(intent)
        }

        downloader.execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=25/xml")
    }

    override fun onDestroy() {
        super.onDestroy()
        downloader.cancel(true)
    }
}

ViewHolder很简单:

class ViewHolder(view: View) {
    val tvName: TextView = view.findViewById(R.id.tvName)
    val tvSummary: TextView = view.findViewById(R.id.tvSummary)
}

我的ListView使用feed_stub.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <TextView
            android:text="TextView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/tvName" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginEnd="16dp" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="16dp" android:textSize="20sp" android:textStyle="bold" android:maxLines="2"
            android:clickable="true"/>
    <TextView
            android:text="TextView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/tvSummary"
            app:layout_constraintTop_toBottomOf="@+id/tvName" app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginEnd="16dp" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="16dp" android:maxLines="3" android:clickable="true"/>
</android.support.constraint.ConstraintLayout>

最后是我的FeedAdapter

class FeedAdapter(context: Context,
                  private val resource: Int, private val feed: MutableList<Any?>)
    : ArrayAdapter<Article>(context, resource) {

    private val inflater = LayoutInflater.from(context)

    override fun getCount(): Int {
        return feed.size
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val viewHolder: ViewHolder
        if(convertView == null) {
            view = inflater.inflate(resource, parent, false)
            viewHolder = ViewHolder(view)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }

        val currentEntry = feed[position] as SyndEntry

        viewHolder.tvName.text = currentEntry.title
        viewHolder.tvSummary.text = currentEntry.description.value

        return view
    }

    override fun isEnabled(position: Int): Boolean {
        return true
    }
}

大多数操作由我的伪控制器执行:

class Downloader(context: Context, listView: ListView): AsyncTask<String, Void, String>() {
    private val TAG = "Downloader"

    private var propContext: Context by Delegates.notNull()
    private var propListView: ListView by Delegates.notNull()

    init {
        propContext = context
        propListView = listView
    }

    private lateinit var list: MutableList<Any?>

    override fun doInBackground(vararg url: String?): String {
        val input = SyndFeedInput()
        val feed = input.build(XmlReader(URL(url[0])))

        list = feed.entries

        return feed.toString()
    }

    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)

        val feedAdapter = FeedAdapter(propContext, R.layout.feed_stub, list)
        propListView.adapter = feedAdapter
    }
}

那为什么我的ListView项目无法点击?

为什么用java.lang.IndexOutOfBoundsException: Invalid index 10, size is 0多次单击后我的应用程序崩溃?

编辑:在FeedAdapter的{​​{1}}中,我添加了此onClickListener:

getView()

现在我可以在某些时候单击它。我绝对不知道为什么会这样,但是如果我随机地单击一下,我将获得进行其他活动的预期行为。

1 个答案:

答案 0 :(得分:0)

这是因为尚未为viewHolder类实现onClickListener。您已经实现了listview onItemClick侦听器,这对于自定义适配器根本不起作用。对于自定义适配器,您需要在getView方法内实现onClickListener。

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val viewHolder: ViewHolder
        if(convertView == null) {
            view = inflater.inflate(resource, parent, false)
            viewHolder = ViewHolder(view)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }

        val currentEntry = feed[position] as SyndEntry

        viewHolder.tvName.text = currentEntry.title
        viewHolder.tvSummary.text = currentEntry.description.value

        // set onClickListener for your ConvertView...
        convertView.setOnClickListener(context);    

        return view
    }

// now implement your on Click 
@Overriden
void onClick(View view){

}