Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: onClick responds only to second click in listview

I found a similar question about scrolling listview and button click but it did not help me. My issue is:

I have a listview with custom rows. I have two different states of listview; the switch between the states is a button at the bottom of the screen. The second state has delete buttons in every row. When I click on delete button in a specific row, that row is removed from database and listview is updated. Everything works great except I need to click the delete button twice in order for it to work. Below is my code for handling the clicks. flag==1 is the second state of the listview.

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 parent view's focusableInTouchMode attribute to false as suggested in another post but it did not help.

If you can help me solve this I will be grateful,

Thank you in advance.

like image 837
Engin Yapici Avatar asked Oct 31 '11 21:10

Engin Yapici


3 Answers

Probably you have focus. Remove it.

android:focusableInTouchMode="true"
android:focusable="true"
like image 140
Mohamed Avatar answered Nov 15 '22 23:11

Mohamed


You need to declare the onClickListener before the actual flag check; in your case the view changes and with that the flag, and the listener is set. The next click actually triggers the listener.

Not related, but you should change your second if to an elseif since there is no way it would be called if the first one is called.

like image 2
fsommar Avatar answered Nov 16 '22 00:11

fsommar


After spending hours I figured out how to do it:

I moved my click listener from my main activity class to my custom ListAdapter class and modified it a little like 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 delete button it removes the list both from the ArrayList (the one used in ListAdapter) and from database.

like image 2
Engin Yapici Avatar answered Nov 16 '22 00:11

Engin Yapici