Search code examples
javaandroidonclickonlongclicklistener

How to NOT handle View.onClick() and handle View.onLongClick() in the same time?


I need to handle only long click event of the TextView (and show popupmenu on this event). But in case of just simple clicking I should transfer this event to layout hosting this view.

How to achieve this?

public class MainActivity extends Activity implements OnLongClickListener, OnClickListener {

TextView mTextView;
RelativeLayout mTopLayout;

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

    mTextView = (TextView) findViewById(R.id.mTextView);
    mTopLayout = (RelativeLayout) findViewById(R.id.mTopLayout);

    mTextView.setOnLongClickListener(this);
    mTopLayout.setOnClickListener(this);
    mTextView.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Toast.makeText(this, v.getClass().getName() + " clicked!", Toast.LENGTH_SHORT).show();
    if (v.getId() == R.id.mTextView) {
        ((View) v.getParent()).performClick();
    }
}

...
}

In this way we will receive two sequential click events and there will be two standard click sounds in android. Not good.

Is there some ease way of achieving this?

Here is the xml:

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

    <TextView
        android:id="@+id/mTextView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#FFFF0000"
        android:clickable="false"
        android:focusable="false"
        android:text="@string/hello_world" />

</RelativeLayout>

EDIT: Just to add details. If I will not set onClickListener then clcking in TextView is done without any effect and this event is consumed by mTextView (even if clickable and focusable is set to false in xml) and not passed to mTopLayout


Solution

  • Finally...

    Why at all I need to make this onClickListeners use different handlers? Stupid.

    @Override
    public void onClick(View v) {
        Toast.makeText(this, v.getClass().getName() + " clicked!", Toast.LENGTH_SHORT).show();
        if (v.getId() == R.id.mTextView || v.getId() == R.id.mTopLayout) {
            //do whatever I need
        }
    }
    

    Really simple.