OnTouch Listener

OnTouchListener: Interface definition for a callback to be invoked when a touch event is dispatched to this view. The callback will be invoked before the touch event is given to the view.

onTouch(View v, MotionEvent event): Called when a touch event is dispatched to a view. This allows listeners to get a chance to respond before the target view. 

The MotionEvent object containing full information about the event.

MainActivity.java :

public class MainActivity extends Activity {
      
       ImageView iv;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              iv = (ImageView) findViewById(R.id.imageView1);
              iv.setOnTouchListener(new OnTouchListener() {
                    
                     @Override
                     public boolean onTouch(View v, MotionEvent event) {
                           if(event.getAction() == MotionEvent.ACTION_DOWN) {
                       // Button was pressed, change button background
                       iv.setImageResource(R.drawable.flagn);
                       Toast.makeText(MainActivity.this, "I love my India !", Toast.LENGTH_SHORT).show();
                       return true;
                   }
                           return false;
                     }
              });
             
             
             
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }

}

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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="96dp"
        android:layout_marginTop="40dp"
        android:src="@drawable/flag" />

</RelativeLayout>


 



**********************************************************************************************************

Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mbl: 9953584548
Write us at: - smruti@apextgi.com and pratap@apextgi.com

No comments:

Post a Comment