Android ListView取消选择项目

标签 android listview

我正在开发一个具有 ListView 的应用程序。在此 ListView 中,当我触摸一个项目时,该项目的背景颜色会发生变化,以表明该项目已被选中。

但是,布局也有一个 EditText:

    <ListView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/pratosListView"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:layout_weight="0.8"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:id="@+id/quantidadeEditText"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
                style="@style/EditText"/>

当我触摸 EditText 时,在 ListView 中选择的项目未被选择,换句话说,背景颜色恢复为原始颜色。我不希望发生这种情况。

这是我的选择器 (list_item_selector.xml):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/item_list_selected"/>
    <item android:state_pressed="true" android:drawable="@drawable/item_list_pressed"/>
    <item android:state_focused="true" android:drawable="@drawable/item_list_focused"/>
    <item android:drawable="@drawable/item_list_normal"/>
</selector>

这里我设置了item的背景(item_lista_pedidos.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/activity_all_magim"
    android:orientation="horizontal"
    android:weightSum="5"
    android:baselineAligned="false"
    android:background="@drawable/list_item_selector">
.....
</LinearLayout>

这里是点击监听器的实现:

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // salva a posicao do item selecionado
        lastPositionSelected = position;
        // salva o objeto relativo ao item selecionado
        servicoSelected = servicos.get(position);
        view.setSelected(true);
    }

有人知道如何避免在我触摸 EditText 时项目被取消选择吗?

最佳答案

如前所述here ,如果你只想检测 EditText 外部的外部触摸,你可以在包含 View 中检测触摸事件,然后,假设你有你的 EditText View :

Rect editTextRect = new Rect();
myEditText.getHitRect(editTextRect);

if (!editTextRect.contains((int)event.getX(), (int)event.getY())) {
    //touch was outside edittext
}

或者您向 EditText 和容器都添加一个触摸监听器,并在其中一个 EditText 中返回 false,这样它将被拦截并且不会转发给父级。因此,您在父级监听器中检测到的所有触摸都不属于 EditText。

关于Android ListView取消选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38592972/

相关文章:

java - 在 android 的共享首选项中禁用对话框通知

php - 使用 Twitter OAuth Echo 进行 verify_credential,如何获取电子邮件?

android - 放大 RecyclerView 中的项目以重叠 2 个相邻的项目 Android

java - Android ContextMenu 更改按钮文本

android - View Holder 稳定性问题

android - android :inputType ="textPersonName" for EditText有什么特别之处

android - 不滚动并显示所有项目的 RecyclerView

android - 如何在 Android ListView Header 上调用点击事件?

java - 使用 edittext 搜索数据 ListView

java - android ListView onclick