Pages

Monday 24 December 2012

android move view horizontally on touch in android 2.2

in this project we have to use following animation library.
this library can be downloaded from http://nineoldandroids.com/

please make following layout named activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/container" >

    <LinearLayout
        android:id="@+id/llMotion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/hello_world" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button" />
    </LinearLayout>

</RelativeLayout>


then use following code to move view vertically on touch


package com.example.viewgesture;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.nineoldandroids.view.ViewPropertyAnimator;

public class MainActivity extends Activity  {
private LinearLayout llMotion;
private RelativeLayout llContainer;
private float default_y = 0;
private Boolean moveable = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llMotion = (LinearLayout) findViewById(R.id.llMotion);
llContainer = (RelativeLayout) findViewById(R.id.container);

llContainer.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {

float y = event.getY();
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN && y >= default_y
&& y < (default_y + llMotion.getHeight())) {
moveable = true;
} else if (action == MotionEvent.ACTION_UP && moveable) {
moveable = false;
default_y = y;
} else if (action == MotionEvent.ACTION_MOVE && moveable) {
ViewPropertyAnimator.animate(llMotion).y(y);

}

return true;

}
});

}


}

No comments :

Post a Comment