Elm Liu
Elm Liu

Reputation: 65

How to handle onClick or onTouch event in my custom class?

I have a custom class MyFloatingButton which inherits nothing. I'd like to handle onClick or onTouch event in it. How to do it? The constructor function receives context, activity and view from activity:

public MyFloatingButton(Context context, RootActivity activity, View view) {
        this.context = context;
        this.activity = activity;
        this.activityView = view;
        getViews();
        initCircleSelector();
    }
private void getViews() {

        floatingActionButton = (FloatingActionButton) activityView.findViewById(R.id.btn_publish);
        circle_selector = (FrameLayout) activityView.findViewById(R.id.circle_selector);
        selector_text = (LinearLayout) activityView.findViewById(R.id.selector_text_div);
        shade_cover = (FrameLayout) activityView.findViewById(R.id.shade_cover);
    }

I tried doing the same things in class MyFloatingButton as it's an Activity. But it didn't work.

Upvotes: 0

Views: 230

Answers (2)

Ricardo
Ricardo

Reputation: 9656

A way to do it is to implement a click listener and then set it to the View in the constructor.

Example:

public MyFloatingButton implements View.OnClickListener {

    public MyFloatingButton(Context context, RootActivity activity, View view) {
        this.context = context;
        this.activity = activity;
        this.activityView = view;
        getViews();
        initCircleSelector();
        activityView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        // handle click event
    }

    .....

}

Do the same for OnTouch

Upvotes: 1

Valeri Iordanov
Valeri Iordanov

Reputation: 21

Your custom class should extend the class "View" in order to have access to the method onClick and onTouch

In my opinion it's better to extend the class "FloatingActionButton"

Those methods are implemented in the class View. So in order for you to have access, your class have to inherit View or anything I showed you.

Upvotes: 0

Related Questions