ListView项目无法点击。为什么?

30

我有一个使用自定义适配器的ListView,但是我无法单击ListView项。

与列表视图相关的活动..

package com.adhamenaya.projects;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.adhamenaya.classes.Place;

public class PlacesListActivity extends Activity {
    private ArrayList<Place> places;
    private ArrayList<String> items;
    GridviewAdapter mAdapter;
    private ListView lvPlaces;
    private EfficientAdapter adap;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.places_list);
        lvPlaces = (ListView) this.findViewById(R.id.lvPlaces);
        new DowanloadPlaces().execute("");
    }
    private void bindList(ArrayList<Place> places) {
        this.places = places;
        // Start creating the list view to show articles
        items = new ArrayList<String>();
        for (int i = 0; i < places.size(); i++) {
            items.add(String.valueOf(places.get(i).mName));
        }
        adap = new EfficientAdapter(this);
        adap.notifyDataSetChanged();
        lvPlaces.setAdapter(adap);
    }

    // EfficientAdapter : to make a customized list view item
    public class EfficientAdapter extends BaseAdapter implements Filterable {

        // The function of inflater to convert objects from XML layout file (i.e. main.xml) to a programmable 
        LayoutInflater inflater;
        Context context;

        public EfficientAdapter(Context context) {
            inflater = LayoutInflater.from(context);
            this.context = context;
        }

        public int getCount() {
            // Get the number of items in the list
            return items.size();
        }

        public Object getItem(int position) {
            // To return item from a list in the given position 
            return items.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        public View getView(final int position, View convertView,ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adaptor_content, null);

                holder = new ViewHolder();// Create an object to hold at components in the list view item
                holder.textLine = (TextView) convertView.findViewById(R.id.textLine);
                holder.buttonLine = (Button) convertView.findViewById(R.id.buttonLine);
                holder.buttonLine.setOnClickListener(new OnClickListener() {
                    private int pos = position;

                    public void onClick(View v) {
                        places.remove(pos);
                        bindList(places);// to bind list items
                        Toast.makeText(getApplicationContext(),"Deleted successfuly :)", Toast.LENGTH_LONG).show();
                    }
                });
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            // Bind the data efficiently with the holder.
            holder.textLine.setText(String.valueOf(places.get(position).mName));
            return convertView;
        }

        public Filter getFilter() {
            // TODO Auto-generated method stub
            return null;
        }

    }

    // ViewHolder : class that represents a list view items
    static class ViewHolder {
        TextView textLine;
        Button buttonLine;
    }

    // DownloadRSSFeedsTask: works in a separate thread
    private class DowanloadPlaces extends AsyncTask<String, Void, ArrayList<Place>> {

        @Override
        protected ArrayList<Place> doInBackground(String... params) {
            ArrayList<Place> places = new ArrayList<Place>();
            Place p = new Place();
            for(int i =0;i<25;i++){
                p.mName = "Al Mathaf Hotel";
                places.add(p);              
            }

            return places;
        }

        @Override
        protected void onPostExecute(ArrayList<Place> places) {
            bindList(places);


        }

    }


}

places_list.xml的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"
        android:id="@+id/lvPlaces">

    </ListView>
</LinearLayout>

适配器内容的XML布局

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textLine"
    android:layout_centerVertical="true"
    android:src="@drawable/settings" />

</RelativeLayout>

你的 ListView 的 OnClickListener 在哪里? - Sergey Benner
你看到了什么行为让你认为它不能被点击?你确定ListView项设置为可点击了吗?如果没有,那么onClick事件将不会被生成。通常情况下,如果遇到问题:1.首先尽可能多地进行调试。 2.如果您期望某种行为但它没有发生,请确保您的代码达到了您期望该行为发生的点。如果没有,请发布代码和问题“为什么我的代码没有到达<x>点?”3.如果您遇到崩溃,请发布崩溃消息和堆栈跟踪,然后问“为什么我的代码在这里中止?” - Joe Malin
我也会为任务列表项使用ContextMenu(上下文菜单),例如删除列表项,但这取决于你的选择。 - Sergey Benner
你可以尝试这个解决方案:http://stackoverflow.com/a/10333241/1592183 这个方法帮助我解决了类似的问题。 - Yorgi
检查这个答案。对我有用。https://dev59.com/IWgu5IYBdhLWcg3wDTCj#11624769 - fpr0001
12个回答

140

Android不允许选择具有可聚焦元素(按钮)的列表项。将按钮的XML属性修改为:

android:focusable="false"

它仍然是可点击的,只是不会获得焦点...


10
FYI:这不仅会在按钮上发生,也会在设置了background的TextView上发生。我使用了focusable="false"来解决这个问题。 - Joshua Pinter
我把所有东西都放在android:focusable="false"下面,现在一切都好了:D - aimiliano
我目前遇到了同样的问题。但是我的列表项内有一个 editText。如果我设置 focusable="false",那么我就不能再更改 editText 的值了。有没有什么方法可以解决这个问题? - Derek
我也认为这应该是最佳答案。它有效了。谢谢! - Dinith Rukshan Kumara

27

我在一个只包含单选按钮(RadioButton)的ListView中遇到了同样的问题:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<RadioButton
    android:id="@+id/userNameRadioButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

我在每一行中使用单选按钮来显示默认的项目选择,为了使ListView处理点击事件,我必须使用以下代码:

radioButton.setFocusableInTouchMode(false);
radioButton.setFocusable(false);

或者在XML文件中:

android:focusable="false" 
android:focusableInTouchMode="false"

所以这是一个与焦点相关的问题... 使用上述修改器后,单击会将焦点定向到 ListView。


5
谢谢您的解释!我在我的应用程序中有一个“CheckBox”,并且想知道为什么我可以单击“CheckBox”,但无法单击“ListView”项目。记录一下,复选框(或在您的情况下是单选按钮)可以保持可点击状态,但不能具有焦点。此外,您可以在XML中使用“android:focusable="false" android:focusableInTouchMode="false"”来实现。 - Randy
这对我解决了问题。显然仅在xml中做这个还不够。一旦我以编程方式实现它,它就起作用了。 - user990230
似乎有点奇怪,需要在XML和代码中都设置,但这个解决方案对我很有效。干得好! - Hector
1
FYI:这不仅发生在按钮上,还发生在设置了background的TextView上。我使用了focusable="false"来解决它。 - Joshua Pinter

14

这里的答案对我有用: https://dev59.com/6nLYa4cB1Zd3GeqPTRIF#16536355

主要是在LinearLayout或RelativeLayout中添加了以下内容:

android:descendantFocusability="blocksDescendants"

您还需要从所有XML文件中删除以下内容:

android:focusable="false"
android:focusable="true"
android:clickable="true"
android:clickable="false"

android:descendantFocusability="blocksDescendants" +1 for this - Palak Darji
android:descendantFocusability="blocksDescendants" 已经为我解决了问题 +1 - vida

5

我想在rupps的回答中添加评论,但我没有足够的声望。

如果您使用扩展ArrayAdapter的自定义适配器,则可以在您的类中重写areAllItemsEnabled()和isEnabled(int position):

@Override
public boolean areAllItemsEnabled() {
    return true;
}

@Override
public boolean isEnabled(int position) {
    return true;
}

上述内容解决了我无法点击列表视图的问题。也许这条评论也能帮助其他人,因为“android list not clickable”搜索词在谷歌上相当高。

@MarcioGranzotto 这个答案仅适用于ArrayAdapter。如何使用BaseAdapter实现呢? - Prabs

3
考虑通过指定android:textIsSelectable="true"来使文本值可选。在行的布局中设置textIsSelectable="false",不要听Google的。感谢Lint(不是!)。

感谢点赞。textIsSelectable="false" 应该在设置 android:focusable="false" 之后。下次我会对 Lint 的建议持保留态度 ^^ - Henrique de Sousa
你也可以尝试点赞 :) 很高兴知道又解决了一个问题。 - Henrique de Sousa

2
我正在使用一个视图和按钮,并将它们放在列表视图中,所以我使用了:
android:focusable="false"

对于<button><view>元素...

之后,我在我的列表视图中使用了以下代码,它可以正常工作。

// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.shipping_item_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(listPairedClickItem);

private AdapterView.OnItemClickListener listPairedClickItem = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    Toast.makeText(getBaseContext(), "Item ", Toast.LENGTH_LONG).show();
    }
};

2

尝试以下代码以获得焦点: View.getFocus();


我认为它不再可用。 - Julian Alberto

1

我有一个关于这个问题的有趣发现,虽然有点晚:

如果你的适配器是从ArrayAdapter继承而来的,无论我怎么尝试,onItemClickListener都不会被调用。

然而,如果你的适配器是从BaseAdapter继承而来的(因此必须实现getCount()和getItem(),对于数组来说很简单),它总是被调用。


1
列表视图项目可点击。要使用它,您必须在列表视图上设置项目单击侦听器。然后它会起作用。

你能详细说明一下“设置点击监听器”的操作吗?怎样才能实现呢? - Zapnologica

0
对我来说,问题是我的ListView中的项目设置了clickabletrue

你的意思是将它设置为“false”吗?我在ListView中有一个复合视图,我为复合视图内的每个按钮设置了clickable为false,它可以正常工作。 - Johnny Wu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接