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
You need to use setOnItemClickListener()
and then new android.widget.AdapterView.OnItemClickListener()
not new View.OnItemClickListener()
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
}
Instead of using setOnClickListener
, try to use setOnItemClickListener
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
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.