android - 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);
}
};
解决方案
我们可以使用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);
}
};
推荐阅读
- python - 具有唯一值的 Python Pandas 计数
- python - symspell 拼写校正功能出错
- reactjs - 使用 Vercel 部署 Mern React
- python - 获取错误 add() 在 Django 中得到了一个意外的关键字参数“override_quantity”
- c# - 当 BadRequestResult 应该返回时,当使用 [Produces(text/csv)] 调用控制器时,不可接受 (406) 现在显示给客户端
- python - 使用 blob_dog 的 Blob 计数器
- javascript - 带有模态模式的图像滑块库
- azure-cosmosdb - 如何通过查询获取 cosmosDB 中的数据库或容器大小?
- performance - JMeter - 如何将变量中的每个字母 1 逐 1 连接起来,直到使用 Groovy 语言完成整个单词
- node.js - 我使用带有 Nodejs 的 pg 池从 postgress 数据库中的 API 获取数据。我在二维数组中获取数据每个数组都是蜡烛信息