Soham
Soham

Reputation: 4417

getView() in ArrayApdapter returns wrong position

Can anyone tell me why I am getting position onSwipeRight() method ?

 @Override
    public View getView(final int position, View view, ViewGroup parent) {
        View v = view;
        if(v==null){

        LayoutInflater inflater = context.getLayoutInflater();
        v = inflater.inflate(R.layout.listviewlayout, null);
        holder=new ViewHolder();
        holder. txtTitle = (TextView) v.findViewById(R.id.label);
        holder. date = (TextView) v.findViewById(R.id.textView1);
        holder. time = (TextView) v.findViewById(R.id.textView2);
        holder. b=(Button) v.findViewById(R.id.button1);
        v.setTag(holder);
        Constants.list.setOnTouchListener(new OnSwipeTouchListener() {

            public void onSwipeTop() {
               // Toast.makeText(SavedList.this, "top", Toast.LENGTH_SHORT).show();
            }
            public void onSwipeRight() {
              //  Toast.makeText(SavedList.this, "right", Toast.LENGTH_SHORT).show();
                holder.b.setVisibility(View.VISIBLE);
                int a=position;
                Log.e("ds",String.valueOf(a));

            }
            public void onSwipeLeft() {
                //Toast.makeText(SavedList.this, "left", Toast.LENGTH_SHORT).show();
            }
            public void onSwipeBottom() {
                //Toast.makeText(SavedList.this, "bottom", Toast.LENGTH_SHORT).show();
            }

        });

Upvotes: 1

Views: 167

Answers (2)

chetanmoswal
chetanmoswal

Reputation: 237

getView will be called n number of times, where n is number od childs in listview.

You are setting listener to Constant.list (the same list always) in getView.

So evry time the getView get called a new lister is getting set to Constant.list and then finnaly it will have the last lister set with that position.

Upvotes: 0

DArkO
DArkO

Reputation: 16120

I assume

Constants.list

is a static variable. setting the touch listener on it with

.setOnTouchListener(new OnSwipeTouchListener() is only set to the last row for which getView was called so your logic only works correctly for the last item for which getView was called.

to see how this works try logging position before you set the touch listener. You will notice how many times getView is being called.

Basically getView is being called once every time a row in the list needs to be shown. Lets say there are 5 rows visible on your screen with the listView. when the list is first shown getView will be called 5 times, then as you scroll it will be called again for each row that becomes visible. As you scroll up this happens also for the views that were previously visible but went away due to the scrolling down.

Upvotes: 1

Related Questions