onClick event is not triggering | Android
Asked Answered
A

9

59

I made a very simple test application with one activity and one layout. The onClick doesn't trigger the first time it is pressed, as it should.

The activity:

package com.example.mytest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText ed1 = (EditText) findViewById(R.id.editText1);

        ed1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
                        .show();

            }

        });
    }

}

The layout:

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:ems="10" />

</RelativeLayout>

If you run this application, and click on the second editText and then back on the first one, it will not trigger the onClick. You can keep selecting back and forth and it will not trigger the onClick at all. I need this basic functionality, but haven't been able to think of a way to get it to work. Ideas?

Notice

I have tried all of the methods recommended on my API level 16 physical device and my API level 8 emulator, but I get the same problem.

Clarification

When editText1 is focused and is clicked on, then the onClick method fires. If editText2 is focussed, and then editText1 is clicked, it doesn't fire. Big problem.

Actaeon answered 3/8, 2012 at 6:42 Comment(4)
what is this::xmlns:tools="schemas.android.com/tools"Emeryemesis
r u display only toast ?? try sysout.. shme times toast r not display may b because if key Bord..Thun
I tried system.out, but it works exactly like the toast did.Actaeon
The tools namespace is for the new (r20) developer tool chain. It's part of the app project template.Matti
T
218

Overview, when a user interacts with any UI component the various listeners are called in a top-down order. If one of the higher priority listeners "consumes the event" then the lower listeners will not be called.

In your case these three listeners are called in order:

  1. OnTouchListener
  2. OnFocusChangeListener
  3. OnClickListener

The first time the user touches an EditText it receives focus so that the user can type. The action is consumed here. Therefor the lower priority OnClickListener is not called. Each successive touch doesn't change the focus so these events trickle down to the OnClickListener.

Buttons (and other such components) don't receive focus from a touch event, that's why the OnClickListener is called every time.

Basically, you have three choices:

  1. Implement an OnTouchListener by itself:

     ed1.setOnTouchListener(new OnTouchListener() {
         @Override
         public boolean onTouch(View v, MotionEvent event) {
             if(MotionEvent.ACTION_UP == event.getAction())
                 editTextClicked(); // Instead of your Toast
             return false;
         }
     });
    

    This will execute every time the EditText is touched. Notice that the listener returns false, this allows the event to trickle down to the built-in OnFocusChangeListener which changes the focus so the user can type in the EditText.

  2. Implement an OnFocusChangeListener along with the OnClickListener:

     ed1.setOnFocusChangeListener(new OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if(hasFocus)
                 editTextClicked(); // Instead of your Toast
         }
     });
    

    This listener catches the first touch event when the focus is changed while your OnClickListener catches every other event.

  3. (This isn't a valid answer here, but it is a good trick to know.) Set the focusable attribute to false in your XML:

     android:focusable="false"
    

    Now the OnClickListener will fire every time it is clicked. But this makes the EditText useless since the user can no longer enter any text...

Note:

getApplicationContext() can create memory leaks. A good habit is to avoid using it unless absolutely necessary. You can safely use v.getContext() instead.

Touraco answered 3/8, 2012 at 16:43 Comment(6)
#2 was helpful in my use case - needed to have my custom relative layout button handle both onClick and onBlur. Note that if anyone has this use case, your onClick will not need to do anything because the onFocusChange handles both the onClick (when hasFocus = true) and onBlur (when hasFocus = false). And if you are using the same type of view, make sure and set android:focusable="true" and android:focusableInTouchMode="true". Thank you, Sam.Adalie
I have a TextView with android:textIsSelectable="true". So what is the solution if I have to listen to OnClick() event and also, the user can select the text within the TextView.Ferrous
Btw, @Touraco do your remember seeing this somewhere in the docs or is it from experience and maybe debugging?Kirstenkirsteni
I learned this the hard way through trial and error then debugging.Touraco
Can you explain how getApplicationContext() creates memory leaks? Doesn't getApplicationContext() return a Singleton instance of Context with Application scope? Slightly OT, but any clarification will be appreciated! Thank you!Chasteen
Solution #3 worked for me since I want to let the user select a date (and see it afterwards), but only through using a DatePickerDialog that pops up on clicking the EditText. This lets the user see that the field is editable, but only lets them change it through the date picker as expected. Thanks a bunch!Verrocchio
A
7

I'm probably too late to the party, but here is a code snipped which fixes the issue with onClick() not being called:

ed1.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && !v.hasFocus()) {
            // onClick() is not called when the EditText doesn't have focus,
            // onFocusChange() is called instead, which might have a different 
            // meaning. This condition calls onClick() when click was performed
            // but wasn't reported. Condition can be extended for v.isClickable()
            // or v.isEnabled() if needed. Returning false means that everything
            // else behaves as before.
            v.performClick();
        }
        return false;
    }
});
Apperception answered 5/5, 2016 at 13:36 Comment(0)
E
5

make edit text clickable.. In XML android:clickable="true" or in code

ed1.setClickable(true);

then do

ed1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
      Toast.makeText(getBaseContext(), "1",Toast.LENGTH_SHORT).show();
    }
  });
Emeryemesis answered 3/8, 2012 at 6:47 Comment(8)
Nope. Still getting the same problem.Actaeon
what is this--> xmlns:tools="schemas.android.com/tools" and remove final from edit text ..Emeryemesis
That's what show's up be default when you create a new layout in eclipse. Also, I removed final and I still get the same problem.Actaeon
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> This the default things..Emeryemesis
Not for mine. That xml is from a brand new project.Actaeon
setClickable(true) was my problem. Not all views set that to true by default. I wasn't using a button, I was using a View which isn't normally clickable.Radie
@Actaeon @Emeryemesis that xmlns:tools doesn't affect the deployed behavior, see tools.android.com/tech-docs/tools-attributes and tools.android.com/tips/layout-designtime-attributesRomeu
@MikeMiller setOnClickListener makes any view clickable, see code.Romeu
W
5

This happens because the first tap gains the focus into the view. The next tap triggers the click.

If you are inflating the view dynamically, do this:

android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"

If this doesn't work, try applying it on the parent view as well.

Wendiwendie answered 4/5, 2017 at 8:28 Comment(0)
J
1

Its the most simplest way to work with date picker.

private DatePickerDialog datePickerDialog;
EditText etJoiningDate;
etJoiningDate=(EditText)findViewById(R.id.etJoiningDate);

etJoiningDate.setOnTouchListener(new View.OnTouchListener() {

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

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:

                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);
                // date picker dialog
                datePickerDialog = new DatePickerDialog(TestActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                etJoiningDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                datePickerDialog.show();

                break;
        }


        return false;
    }


});
Johnathon answered 3/5, 2018 at 5:45 Comment(0)
R
0
public class TestProject extends Activity implements OnClickListener {
TextView txtmsg;
EditText ed1, ed2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    txtmsg = (TextView) findViewById(R.id.txtmsg);
    ed1 = (EditText) findViewById(R.id.edt1);
    ed2 = (EditText) findViewById(R.id.edt2);

    ed1.setOnClickListener(this);
    ed2.setOnClickListener(this);
}

@Override
public void onClick(View v) {


    if(v==ed1){
        txtmsg.setText("1");
        Toast.makeText(this, "first",Toast.LENGTH_SHORT).show();
    }
    if(v==ed2){
        txtmsg.setText("2");
        Toast.makeText(this, "second",Toast.LENGTH_SHORT).show();
    }

}

}

<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" >

    <EditText
        android:id="@+id/edt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <EditText
        android:id="@+id/edt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/edt1"
        android:layout_marginTop="14dp"
        android:ems="10" />

    <TextView
        android:id="@+id/txtmsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/edt2"
        android:layout_below="@+id/edt2"
        android:layout_marginRight="22dp"
        android:layout_marginTop="160dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
Repartition answered 3/8, 2012 at 10:12 Comment(0)
D
0

Took me a minute to figure this out one time when this happened to me. My ImageButton with a setOnClickListener and onClick didn't seem to fire and then I realized it was actually underneath another element in my xml layout, so I turned this:

 <RelativeLayout>
     <ImageButton>
     <LinearLayout></LinearLayout>
 </RelativeLayout>

into this:

 <RelativeLayout>
     <LinearLayout></LinearLayout>
     <ImageButton>
 </RelativeLayout>

and suddenly the ImageButton was not being overlapped by the other layout since it was now added later to the parent layout and was now on top and works every time. Good luck, always fun when basic stuff suddenly seems to stop working

Depositary answered 20/9, 2015 at 4:9 Comment(0)
N
0

Avoid using a FocusChangeListener since it will behave erratically when you don't really need it (eg. when you enter an activity). Just set an OnTouchListener along with your OnClickListener like this:

@Override
public boolean onTouch(View view, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            view.requestFocus();
            break;
    }
    return false;
}

This will cause your EditText to receive focus at first, and your onClick to function properly the first time.

Nichani answered 7/11, 2016 at 19:37 Comment(0)
D
0

Simple, Reuseable Kotlin Solution

I started with two custom extension functions:

val MotionEvent.up get() = action == MotionEvent.ACTION_UP

fun MotionEvent.isIn(view: View): Boolean {
    val rect = Rect(view.left, view.top, view.right, view.bottom)
    return rect.contains((view.left + x).toInt(), (view.top + y).toInt())
}

Then listen to touches on the Edittext. This will only fire if initial ACTION_DOWN event was originally on the Edittext, and still is.

myEdittext.setOnTouchListener { view, motionEvent ->
    if (motionEvent.up && motionEvent.isIn(view)) {
        // Talk your action here
    }
    false
}
Demy answered 31/1, 2020 at 2:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.