user387184
user387184

Reputation: 11053

Adding OnTouchListener to each line of ListView in ListFragment

Actually I thought the ListView of a ListFragment would have been created in OnActivityCreated.

  @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

        ...initialize the namesList

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_1, namesList);
    setListAdapter(adapter);

    }

Then I access the ListView in onResume to add a OnTouchListener to each row in the list (=the children) However there are no children added to the ListView yet - even though they should be due to the code above in onActivityCreated one should expect.

  @Override
    public void onResume() {
    super.onResume();
    ListView lv = getListView();
    int n1 = lv.getChildCount();
    for (int ii = 0; ii < n1; ii++) {
        View lineV = lv.getChildAt(ii);
        lineV.setOnTouchListener(new MyTouchListener());
    }

    }

So the last chance to add the OnTouchListener is in OnListItemClick. (since there are no children in the ListView before)

   @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    v.setPressed(false);

    ListView lv = getListView();
    int n1 = lv.getChildCount();
    for (int ii = 0; ii < n1; ii++) {
        View lineV = lv.getChildAt(ii);
        lineV.setOnTouchListener(new MyTouchListener());
    }

    }

But even here the OnTouchListeners have still not been added to the displayed lines.

Only after couple of times touching some lines in the displayed names list finally the OnTouchListener have been added and intercept the touches.

But until then the normal onListItemClick catches the touches - which I just don't want to happen.

All I need is to add the OnTouchListeners to each line in a ListView from THE VERY BEGINNING when the list is displayed so I can do whatever I want instead of let the OnListItemClick handle the event.

(I actually want to drag the line around while pressing the line - OnListItemClick only starts AFTER the line has been untouched)

Many thanks!

Upvotes: 0

Views: 2477

Answers (2)

J.S.
J.S.

Reputation: 31

Override onViewCreated and add your listener there

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ListView listView = getListView();
    MyListViewTouchListener touchListener =
        new MyListViewTouchListener (listView);
    listView.setOnTouchListener(touchListener); 
}

Upvotes: 1

louielouie
louielouie

Reputation: 14941

I've done something similar before in terms of adding a listener to each row in a list view.

What you need to do is to create a subclass of ArrayAdapter. Then in the getView() method, set your MyTouchListener as the onTouchListener to your view before returning it.

Upvotes: 0

Related Questions