ListView的OnItemLongClickListener()没有被触发

6
我有一个继承了ListActivity的类,其中列表项响应OnClick事件。添加OnItemLongClickListener不起作用。onItemLongClick()函数没有被调用(没有日志输出或显示Toast),而是处理常规的OnClick()事件。
我想在长按时显示上下文操作栏。在新项目中使用我的代码的最小示例可以正常工作。因此,我的问题是:可能会防止触发onItemLongClick()触发器的是什么?
我的最低API为11。我还将listView设置为longClickable="true"。
活动代码(选定功能):
public class EventListActivity extends ListActivity {

    private ArrayList<Event> arrEvents = null;
    private ArrayAdapter<Event> adpEvents = null;

    private ActionMode mActionMode = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // only create list adapter and set it
        arrEvents = new ArrayList<Event>();
        adpEvents = new ArrayAdapter<Event>(this, android.R.layout.simple_list_item_activated_2, android.R.id.text1, arrEvents) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                TextView text2 = (TextView) view.findViewById(android.R.id.text2);
                text1.setText(arrEvents.get(position).getTitle());
                text2.setText(arrEvents.get(position).getDateTimeFormatted());
                return view;
            }
        };

        setListAdapter(adpEvents);

        // add CAB to ListView
        setupCAB();
    }


    @Override
    protected void onResume() {
        super.onResume();

        // populate list and refresh adapter
        createEventList();
        adpEvents.notifyDataSetChanged();

        // if list empty show emtpy msg, otherwise hide it
        setContentView(R.layout.activity_event_list);
        TextView empty = (TextView) findViewById(R.id.text_empty);
        if(arrEvents.isEmpty()) {
            empty.setVisibility(View.VISIBLE);
        } else {
            empty.setVisibility(View.GONE);
        }
    }


    private void setupCAB() {
        // Important: to select single mode
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            // Called when the user long-clicks an item on the list
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View row, int position, long rowid) {
                Log.w("EventListActivity", "Long click detected!");
                Toast.makeText(EventListActivity.this, "Long click detected!", Toast.LENGTH_SHORT).show();
                if (mActionMode != null) {
                    return false;
                }

                // Important: to mark the editing row as activated
                getListView().setItemChecked(position, true);

                // Start the CAB using the ActionMode.Callback defined above
                mActionMode = EventListActivity.this.startActionMode(mActionModeCallback);
                return true;
            }
        });
    }

    private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        // Called when the action mode is created; startActionMode() was called
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.event_context, menu);
            return true;
        }

        // Called when the user enters the action mode
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Disable the list to avoid selecting other elements while editing one
            EventListActivity.this.getListView().setEnabled(false);
            return true; // Return false if nothing is done
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.mnu_share_event:
                //TODO share event
                mode.finish();
                return true;
            default:
                return false;
            }
        }

        // Called when the user exits the action mode
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // Re-enable the list after edition
            EventListActivity.this.getListView().setEnabled(true);
            mActionMode = null;
        }
    };

}

activity_event_list.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".EventListActivity" >

    <TextView
        android:id="@+id/text_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="@string/empty"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:visibility="gone" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:longClickable="true" >
    </ListView>

</RelativeLayout>
3个回答

5

如果你的列表视图中有响应onClick()事件的按钮,你需要在包含这些按钮的容器中设置以下内容:

android:descendantFocusability="blocksDescendants"

如果你有的是TextView,那么问题稍微麻烦一些。请参考这个链接:ListView中可聚焦的EditText

谢谢,但是我的ListView里没有按钮或EditText视图。就像我在问题中发布的那样,只有普通的TextView(android.R.layout.simple_list_item_activated_2)。 - MoRe
你试过无论如何添加blocksDescendants吗? - Ricardo
1
是的,但它并没有改变任何东西,因为我的问题源于不同的原因(请参见我在Rick Falck答案下的评论)。 - MoRe

2

这个答案并没有解决用户1的问题,但症状与我的问题相似(即OnItemClickListener被调用,但OnItemLongClickListener没有被调用)。我将我的答案发布在这里,以防其他人像我一样在尝试解决自己的问题时偶然发现了这个问题。

我在一个Fragment中使用了一个ListView,并实现了监听器方法:

public class MyFragment extends Fragment implements OnClickListener,
        OnLongClickListener, OnItemClickListener, OnItemLongClickListener {

这里是正常工作的onItemClick方法:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long rowId) {

    Log.i("Chimee", "short click working");

}

这里是未触发的onItemLongClick方法:

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
        long rowId) {

    Log.i("Chimee", "Long click working");
    return false;
}

当然,简单的答案是我忘记了setOnItemLongClickListener。在我一直拥有的setOnItemClickListener之后添加它,然后它就可以正常工作了。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.my_fragment, container, false);

    lvSuggestions = (ListView) v.findViewById(R.id.lvSuggestions);
    lvSuggestions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    lvSuggestions.setOnItemClickListener(this);
    lvSuggestions.setOnItemLongClickListener(this); // Forgot this

    ...
}

1
使用ListActivity或ListFragment时,没有方法可以覆盖长按事件,并且在onCreateView()中无法访问ListView,因为它由父类控制。为了解决这个问题,可以在视图创建后使用getListView()命令进行访问。
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mRecipeListView = this.getListView();
    mRecipeListView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long row_id) {
            // Process the long-click
        }
    });
}

谢谢,答案在你的最后一句话中:“因为在视图创建之前getListView()命令不起作用”。我在调用setContentView(R.layout.activity_event_list);之前调用了我的setupCAB()方法,所以列表视图还没有准备好。但是我仍然不明白我应该把你的代码放在哪里... - MoRe

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