Set long click listener for listview

后端 未结 5 527
心在旅途
心在旅途 2021-01-17 17:31

I have below codes:

public class MainActivity extends ListActivity { 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceSt         


        
5条回答
  •  悲&欢浪女
    2021-01-17 17:52

    Your question is very similar to this one, but it looks like it's not an exact duplicate.

    What you've noticed is that the ListActivity class does not have a method override specifically for this case.

    In order to add this functionality as a method override, your class should implement the AdapterView.OnItemLongClickListener interface, and then you can add the onItemLongClick() method override, which acts just as the onListItemClick() method override you already have, but responds to long clicks.

    Just make sure that you follow instructions from this answer, you must use android:longClickable="true" in the layout xml, or call listview.setLongClickable(true);

    Example:

    public class MainActivity extends ListActivity implements AdapterView.OnItemLongClickListener {
    
        ListView listview;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ListView listview = (ListView) findViewById(R.id.list);
    
            listview.setLongClickable(true);
    
        }
    
        @Override
        public boolean onItemLongClick(AdapterView l, View v,
                                       final int position, long id) {
    
            Toast.makeText(this, "long clicked pos: " + position, Toast.LENGTH_LONG).show();
    
            return true;
        }
    
        protected void onListItemClick(ListView l, View v, final int position, long id) {
            super.onListItemClick(l, v, position, id);
    
            Toast.makeText(this, "short clicked pos: " + position, Toast.LENGTH_LONG).show();  
    
        }
    
     //....................
    

提交回复
热议问题