Android: onClick only responds to the second click in the list

I found a similar question about scrolling through a list and clicking a button, but that didn't help me. My problem:

I have a listview with custom strings. I have two different list states; the switch between states is a button at the bottom of the screen. The second state has delete buttons on each line. When I click the delete button on a specific row, that row is deleted from the database and the list is updated. Everything works fine, except that I need to double-click the "Delete" button to make it work. Below is my click processing code. flag == 1 is the second state of the list.

public void onItemClick(AdapterView<?> parent, View v, int position, long id) { View main = parent.getChildAt(position); TextView delete = (TextView)main.findViewById(R.id.delete_button); if(flag==0){ switchToItemsView(id); } if(flag==1){ delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDbHelper.deleteList(id); updateListView(); }}); } } 

I tried to set the focusableInTouchMode parent view attribute to false, as suggested in another post, but that didn't help.

If you can help me, I will be grateful

Thanks in advance.

+4
source share
3 answers

After spending hours, I figured out how to do this:

I moved my click listener from my main activity class to my own ListAdapter class and slightly modified it below:

 deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int rowid = Integer.parseInt(rowIds.get(position)); mDb.deleteList(rowid); lists.remove(position); notifyDataSetChanged(); } }); 

Now it works great. When I click the Delete button, it removes the list from both the ArrayList (the one used in the ListAdapter) and the database.

+2
source

Perhaps you have a focus. Remove it.

 android:focusableInTouchMode="true" android:focusable="true" 
+4
source

You need to declare onClickListener before actually checking the flag; in your case, the view changes, and with this the flag and listener are set. The next click actually calls the listener.

Not connected, but you have to change your second if to elseif , because it will not be called if the first is called.

+2
source

Source: https://habr.com/ru/post/1379025/


All Articles