2

I am working on an android app and I have a custom GUI component which extends a TextView.

I want to have my custom control do a task when clicked from my custom control class and my overridden onclick method.

For example my class that extends the TextView implements the OnClick listener and writes a log to the log cat.

Then in my activity, I set an onclick listener to my custom control, and this shows a toast notification.

What I want to happen, is when my custom control is clicked, my activities overridden onclick shows the toast and the custom control class on click method also is run to show the log. But I can only seem to get one working or the other, for example, if I don't run myCustom.setOnClickListener(myListener) then the classes onclick is used and does the log, if I set the onClick listener then I only get the toast not the log.

Below is my custom control class

public class NavTextView extends TextView implements View.OnClickListener
{
    public NavTextView(Context context) {
        super(context);
        setOnClickListener(this);
    }

    public NavTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
    }

    public NavTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(this);
    }

    public NavTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.d("NavTextView", "This has been clicked");
    }
}

Below is my activities onCreate method

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

        navTextView = (NavTextView)findViewById(R.id.navTextView);

        navTextView.setOnClickListener(mClickListener);
    }

Hope this makes sense

Boardy
  • 35,417
  • 104
  • 256
  • 447

1 Answers1

9

A View can only have one OnClickListener. In your NavTextView you are setting it there. If you later call setOnClickListener again, you are replacing the previous listener.

What you can do is override setOnClickListener in your custom View, then wrap the OnClickListener and call both.

public class MyTextView extends TextView implements View.OnClickListener
{
    OnClickListener _wrappedOnClickListener;

    public MyTextView(Context context) {
        super(context);
        super.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        Log.d("NavTextView", "This has been clicked");

        if (_wrappedOnClickListener != null)
            _wrappedOnClickListener.onClick(view);
    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        _wrappedOnClickListener = l;
    }
}
Jeffrey Mixon
  • 12,846
  • 4
  • 32
  • 55