Friday, September 16, 2011

Scroll the image both horizontal and vertically


main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <FrameLayout android:layout_width="90px"
        android:layout_height="90px">
        <RelativeLayout android:id="@+id/container"
            android:layout_width="fill_parent" android:layout_height="fill_parent">
        </RelativeLayout>
    </FrameLayout>
</FrameLayout>


Test.Java

public class Test extends Activity
{
    private RelativeLayout container;
      private int currentX;
      private int currentY;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        container = (RelativeLayout)findViewById(R.id.container);

        int top = 0;
        int left = 0;

        ImageView image1 =new ImageView(this);
        image1.setImageResource(R.drawable.icon);//set the image whatever u scroll
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(left, top, 0, 0);              
        container.addView(image1, layoutParams);

       
      }    

      @Override
      public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                currentX = (int) event.getRawX();
                currentY = (int) event.getRawY();
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                int x2 = (int) event.getRawX();
                int y2 = (int) event.getRawY();
                container.scrollBy(currentX - x2 , currentY - y2);
                currentX = x2;
                currentY = y2;
                break;
            }  
            case MotionEvent.ACTION_UP: {
                break;
            }
        }
          return true;
      }
    }

No comments:

Post a Comment