Android Linearlayout Ontouchlistener onclicklistener Example

Previous article Android LinearLayout Example has introduced how to use LinearLayout to layout and align components in android app. This article will show you an example about how to implement on touch listener and on click listener to the LinearLayout object.

Android LinearLayout OnTouchListener onclickListener Example

1. Main Layout Xml File.

<LinearLayout android:id="@+id/linearLayoutExample" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register"/> <Button android:id="@+id/linearLayoutExampleResetButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Reset"/></LinearLayout>

2. Activity Java Code.

Please Note: If the on touch listener’s onTouch method return true, then the on click listener will not be invoked. So the onTouch method return false by default.

Of course if you want to avoid on click after on touch, you can make the onTouch method return true.

package com.dev2qa.example;import android.os.Bundle;import;import android.view.MotionEvent;import android.view.View;import android.widget.LinearLayout;import*;import android.widget.Toast;public class LinearLayoutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_linear_layout); setTitle(" - Android LinearLayout Example"); // First get the LinearLayout object. LinearLayout linearLayout = (LinearLayout)findViewById(; // Implement it's on click listener. linearLayout.setonclickListener(new View.onclickListener() { @Override public void onclick(View view) { // Show a toast message. Toast.makeText(LinearLayoutActivity.this, "You clicked the Linear Layout", Toast.LENGTH_SHORT).show(); } }); // Implement it's on touch listener. linearLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // Show an alert dialog. AlertDialog alertDialog = new AlertDialog.Builder(LinearLayoutActivity.this).create(); alertDialog.setMessage("You touched the Linear Layout.");; // Return false, then android os will still process click event, // if return true, the on click listener will never be triggered. return false; } }); }}
  • 199