onItemClick()接收布局而不是TextView

时间:2018-12-13 18:22:54

标签: android listview android-constraintlayout onitemclicklistener

我的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);
        }
    };

1 个答案:

答案 0 :(得分:0)

我们可以使用 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);
        }
    };