Java ListView OnItemLongClickListener()未触发

Java ListView OnItemLongClickListener()未触发,java,android,listview,contextual-action-bar,Java,Android,Listview,Contextual Action Bar,我有一个扩展ListActivity的类,其中列表项响应OnClick事件。添加OnItemLongClickListener无效。不会调用onItemLongClick()函数(无日志输出或Toast显示),而是处理正常的OnClick()事件 我想在长时间单击后显示上下文操作栏。在一个新项目中使用我的代码的最低限度的示例可以很好地工作。所以我的问题是:什么可能阻止触发onItemLongClick()触发器 我的最低API是11。我还将listView设置为longClickable=“tr

我有一个扩展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;
        }
    };

}
<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>
公共类EventListActivity扩展了ListActivity{
private ArrayList arredents=null;
private ArrayAdapter adpEvents=null;
私有操作模式mActionMode=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//仅创建列表适配器并设置它
arreavents=newarraylist();
adpEvents=new ArrayAdapter(这个,android.R.layout.simple\u list\u item\u activated\u 2,android.R.id.text1,ArraEvents){
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图=super.getView(位置、转换视图、父级);
TextView text1=(TextView)view.findViewById(android.R.id.text1);
TextView text2=(TextView)view.findViewById(android.R.id.text2);
text1.setText(arevents.get(position.getTitle());
text2.setText(arevents.get(position.getDateTimeFormatted());
返回视图;
}
};
setListAdapter(adpEvents);
//将CAB添加到ListView
setupCAB();
}
@凌驾
受保护的void onResume(){
super.onResume();
//填充列表并刷新适配器
createEventList();
adpEvents.notifyDataSetChanged();
//如果列表为空,则显示emtpy消息,否则将其隐藏
setContentView(R.layout.activity\u event\u list);
TextView empty=(TextView)findViewById(R.id.text\u empty);
if(arreavents.isEmpty()){
empty.setVisibility(View.VISIBLE);
}否则{
empty.setVisibility(View.GONE);
}
}
私有void setupCAB(){
//重要事项:选择单一模式
getListView().setChoiceMode(ListView.CHOICE\u MODE\u SINGLE);
getListView().setOnItemLongClickListener(新的AdapterView.OnItemLongClickListener()){
//当用户长时间单击列表中的项目时调用
@凌驾
公共布尔值长单击(AdapterView父项、视图行、整型位置、长rowid){
w(“EventListActivity”,“检测到长时间单击!”);
Toast.makeText(EventListActivity.this,“长点击检测!”,Toast.LENGTH\u SHORT.show();
if(mActionMode!=null){
返回false;
}
//要点:将编辑行标记为已激活
getListView().setItemChecked(位置,true);
//使用上面定义的ActionMode.Callback启动CAB
mActionMode=EventListActivity.this.startActionMode(mActionModeCallback);
返回true;
}
});
}
private ActionMode.Callback mActionModeCallback=new ActionMode.Callback(){
//创建操作模式时调用;调用startActionMode()
@凌驾
公共布尔onCreateActionMode(ActionMode模式,菜单){
//为提供上下文菜单项的菜单资源充气
MenuInflater充气器=模式。getMenuInflater();
充气器。充气(右菜单。事件上下文,菜单);
返回true;
}
//当用户进入操作模式时调用
@凌驾
公共布尔onPrepareActionMode(操作模式,菜单){
//禁用该列表以避免在编辑一个元素时选择其他元素
EventListActivity.this.getListView().setEnabled(false);
return true;//如果不执行任何操作,则返回false
}
//当用户选择上下文菜单项时调用
@凌驾
公共布尔值onActionItemClicked(ActionMode模式,菜单项){
开关(item.getItemId()){
案例R.id.mnu\U共享\U事件:
//待办事项分享活动
mode.finish();
返回true;
违约:
返回false;
}
}
//当用户退出操作模式时调用
@凌驾
公共void onDestroyActionMode(ActionMode模式){
//编辑后重新启用列表
EventListActivity.this.getListView().setEnabled(true);
mActionMode=null;
}
};
}
activity\u event\u list.xml:

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;
        }
    };

}
<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>

如果在listview中有响应
onClick()
事件的按钮,则需要在保存这些按钮的容器中设置以下内容:

android:descendantFocusability="blocksDescendants"

如果您拥有的是文本视图,那么问题就稍微复杂一些。请参见:

当使用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
        }
    });
}
@覆盖
已创建视图上的公共void(视图,捆绑保存状态){
super.onViewCreated(视图,savedInstanceState);
mRecipeListView=this.getListView();
mRecipeListView.setOnItemLongClickListener(新的ListView.OnItemLongClickListener(){
@凌驾
公共布尔值长单击(AdapterView arg0,视图,int p
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
        long rowId) {

    Log.i("Chimee", "Long click working");
    return false;
}
@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

    ...
}