سؤال

Now I want to change the top margin(10 px down in every touch event) of img1 in every touch event.Below is my code.I have put this code in the touch event of my activity.

  public static int  count=0;

        int place=-300;
                System.out.println("Count is:"+count);
                if(count>0)
                {
                    LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(0, place, 0, 0);
                        ImageView imageView=(ImageView)findViewById(R.id.img1);
                    //  MarginLayoutParams marginLayoutParams=new MarginLayoutParams(imageView.getLayoutParams());
                        //marginLayoutParams.setMargins(0, 500, 0, 0);
                        imageView.setLayoutParams(lp);
                        place=place+10;

                }
    count++; 

Now the margin is changed only in one touch event not in every touch event.

So I want that every touch of user the image should come down by 10 px

هل كانت مفيدة؟

المحلول

if for every touch event above code executes... local "place" variable will be initialized to -300 each time , hence place = place + 10 will always result -290 px , please declare place variable in class level , like your count variable. Hope, this will work for you.

نصائح أخرى

One note here, you are declaring your "count" variable to be 0 everytime your touch event fires, in case you were wondering why it doesn´t increment.

What you are effectively doing here is creating a new ImageView in every touch event. You should refer to the same ImageView if you want to consistently work on that object, not declare it everytime you want to do something with it.

Try declaring it in the top of your Activity class:

public ImageView imageView;

Then you can instantiate it in your onCreate method:

imageView=(ImageView)findViewById(R.id.img1);

And then you can work on it in your touch event, without declaring it each time:

   if(count>0)
        {
            LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, place, 0, 0);
            //  MarginLayoutParams marginLayoutParams=new MarginLayoutParams(imageView.getLayoutParams());
                //marginLayoutParams.setMargins(0, 500, 0, 0);
                imageView.setLayoutParams(lp); // Note how we havent declared it above.
                place=place+10;

        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top