Spring Breaker
Spring Breaker

Reputation: 8251

How to set OnTouchListener for dynamically created views?

I have two layouts, one LinearLayout and one RelativeLayout. In the LinearLayout I have 10 images. When I click one image, it is added to the RelativeLayout. Similar event is given for all 10 images. In the RelativeLayout, I have set a OnTouchListener to the ImageView added from the LinearLayout. But my problem is, onTouch only works for the ImageView which is recently added but when I try to touch previously added images, it doesn't work. I want to add listener for all images added in the relative layout.

Below is what I have tried so far:

for(int i = 0; i < data.length; i++){
           image[i] = new ImageView(getApplicationContext());
            try{
               // int imgID = getResources().getIdentifier(data[i], null, getPackageName());
                image[i].setImageResource(data[i]);

            }catch(Exception e){
                int imgID = getResources().getIdentifier("nia", "drawable", "package");
                image[i].setImageResource(imgID);
            }         
            LinearLayout.LayoutParams LEye = new LinearLayout.LayoutParams(
                    100 , 70);
            LEye.leftMargin=20;
            image[i].setLayoutParams(LEye);
            shapeImageContainer.addView(image[i]); //shapeImageContainer is the Linear Layout
           final int c=i;
            image[i].setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    //addContentView( addIcon(), new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
                    Toast.makeText(NewProject.this, "Position "+c, Toast.LENGTH_SHORT).show();

                    rootView.addView(addIcon(c)); //rootView is the Relative layout

                }
            });

            //image[i].setOnTouchListener(MyOnTouchListener);

        }


private ImageView addIcon(int c){
        item = new ImageView(this);
        item.setImageResource(data[c]);
        item.setAdjustViewBounds(true);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 60 );
        if( mIconIdCounter != 1 ){
            params.addRule(RelativeLayout.RIGHT_OF,c-1);
        }
        item.setLayoutParams( params );
        item.setId( mIconIdCounter );
        ++mIconIdCounter;
        item.setOnTouchListener(MyOnTouchListener);
        return item;
    }

    OnTouchListener MyOnTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
//          scroll.setEnabled(false);
//          horizontal.setEnabled(false);

//          scroll.setVisibility(View.GONE);
//          horizontal.setVisibility(View.GONE);
        RelativeLayout.LayoutParams  layoutParams2 = (RelativeLayout.LayoutParams) item.getLayoutParams();
                switch(event.getActionMasked())
                {

                    case MotionEvent.ACTION_MOVE:
                        scroll.requestDisallowInterceptTouchEvent(true);
                        horizontal.requestDisallowInterceptTouchEvent(true);
                        int x_cord = (int) event.getRawX();
                        int y_cord = (int) event.getRawY();

                        //right margin
                        if (x_cord > windowwidth) {
                            x_cord = windowwidth-10;
                        }

                        // left margin original
                        if (x_cord <68) {
                            x_cord = 68;
                        }
                        // left margin original
                        if (y_cord <68) {
                            y_cord = 68;
                        }
                        if (y_cord > windowheight) {
                            y_cord = windowheight-10;
                        }

                       // tv.setText(String.valueOf(y_cord));
                        layoutParams2.leftMargin = x_cord -60;
                        layoutParams2.topMargin = y_cord -65;
                        item.setLayoutParams(layoutParams2);
                        break;
                    default:
                        break;
                }
            return true;
        }

    };

Upvotes: 3

Views: 2031

Answers (1)

user
user

Reputation: 87064

But my problem is, onTouch only works for the imageview which is recently added but when I try to touch previously added images,it doesn't work.

That's because in the OnTouchListener you use the item field to do your work(which will always point to the last ImageView added as you wrote the code) instead of using the View for which the listener is called. Try something like this:

RelativeLayout.LayoutParams  layoutParams2 = (RelativeLayout.LayoutParams) v.getLayoutParams();
// rest of the onTouch callback...
v.setLayoutParams(layoutParams2);

Upvotes: 4

Related Questions