首页 > 解决方案 > onItemClick() 接收布局而不是 TextView

问题描述

我的 Activity 中有一个 ListView,其行由从数据库中获取的登录名填充。我的 ListView 中的每一行都包含一个约束布局内的 TextView。当用户触摸此 ListView 的某一行时,应启动另一个活动。我使用 OnItemClickListener 来实现这一点,一切似乎都很好,但是来自 Listener 的 onClickItem() 方法接收到对 ConstraintLayout 类型对象的引用,我需要从该布局内的 TextView 获取文本。我怎样才能做到这一点?

这是我的一个简单行的 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:id="@+id/row"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:text="TextView"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

这是我对 OnItemClickListener 的实现:

private AdapterView.OnItemClickListener myItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            TextView currentView = (TextView) view; // Here I get an exception that ConstraintLayout cannot be casted to TextView
            String login = currentView.getText().toString();
            Intent intent = new Intent(Powitanie.this,UserPanel.class);
            intent.putExtra(LOGIN, login);
            Powitanie.this.startActivity(intent);
        }
    };

标签: androidlistviewandroid-constraintlayoutonitemclicklistener

解决方案


我们可以使用getChildAt()方法。onItemClick() 接收对视图的引用。我们可以将其强制转换为 ConstraintLayout 并从指定的索引中获取一个子项。

private AdapterView.OnItemClickListener myItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            ConstraintLayout layout = (ConstraintLayout) view;
            TextView currentView = (TextView) layout.getChildAt(0); // In getChildAt we need to specify index of a child. In this case it's 0.
            String login = currentView.getText().toString();
            Intent intent = new Intent(Powitanie.this,UserPanel.class);
            intent.putExtra(LOGIN, login);
            Powitanie.this.startActivity(intent);
        }
    };

推荐阅读