setOnClickListener of a ListView not working

前端 未结 5 1546
挽巷
挽巷 2020-12-09 04:06

So I\'m trying to set up a setOnClickListener for my ListView but it\'s causing a crash in my program for some reason when I try... I\'m quite new

相关标签:
5条回答
  • 2020-12-09 04:51

    You need to use setOnItemClickListener()

    and then new android.widget.AdapterView.OnItemClickListener()

    not new View.OnItemClickListener()

    0 讨论(0)
  • 2020-12-09 04:51

    In my case I try to add onClickListener for spinner and I've got the same problem. I've crated workaround with touch listener. Sometimes we need it for hideKeyBoard or send some analyticEvent:

    someSpinner.setOnTouchListener { _, event ->  onTouchSomeSpinner(event)}
    
    fun onTouchSomeSpinner(event: MotionEvent): Boolean {
            if(event.action == MotionEvent.ACTION_UP) {
                view.hideKeyBoard()
                view.analyticsEvent()
                ...
            }
            return false
    }
    
    0 讨论(0)
  • 2020-12-09 04:53

    Instead of using setOnClickListener, try to use setOnItemClickListener

    0 讨论(0)
  • 2020-12-09 05:01

    If using Butterknife, check that you don't have OnClick annotation for an AdapterView descentant (Spinner, ListView, etc.)

    @OnClick(R.id.spinner_id)
    

    Calling ButterKnife.inject(this, view); will throw the exception

    Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead

    0 讨论(0)
  • 2020-12-09 05:12

    firstly set the value inside your main activity where your using your listview:

    new android.widget.AdapterView.OnItemClickListener()
    

    in place of adapter of your listview:

      new AdapterView.OnItemClickListener() 
    

    So finally it looks like:

    this.listView.setItemsCanFocus(false);
    this.listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(android.widget.AdapterView<?> parent, View view, int position, long id) {
    
     }
    

    when you are using any custom view to populate the data inside listview.

    Then in your main Activity file.xml in the parent layout{ inside which listview is there} set this option:

        android:descendantFocusability="blocksDescendants"
    

    and if you are using any buttons/textview inside listview, set this property on that textview/button:

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

    For scroll option in your listview just add this line inside activity:

     listView=(ListView)findViewById(R.id.container);
     listView.setNestedScrollingEnabled(true);
    

    As per i understood i am giving answer, and i hope it will help, if anyone found some corrections or helpful, they are welcome.

    0 讨论(0)
提交回复
热议问题