idish
idish

Reputation: 3260

setonclicklistener on another activity

Say I have two activities: "A" and "B".

Activity A has a button in it's layout. and I want to set it's click listener implemention on Activity B. So let's say here's Activity A:

Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(B.this);

and in Activity B, I'm trying to implement the function:

public void OnClick(View v)
{
//DO SOMETHING
}

I'm getting the following errors:

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (A)

  • No enclosing instance of the type A is accessible in scope

What am I doing wrong here?

Upvotes: 2

Views: 3445

Answers (2)

Arpit Garg
Arpit Garg

Reputation: 8546

The handling of the GUI components must be accompanied within the same UI thread that instantiated that.

So your desired view is not correct also make sure the you can have the click and other listener been worked only if the view is set with that components and is currently visible ( In foreground) for the user to have interaction.

If you really want that then You can override the default implementation of the click listener within the different activities via following:

1)Static Reference: make the button as public static in activity A and use it in Activity B by Class A's name.

2)Interface:implements OnClickListener on the activity A , but will not be accessible in B

3)Custom MyClickListener for all activites.

public class MyClickListener implements OnClickListener {
    @Override
    public void onClick(View v) {
        mContext = v.getContext();

        switch (v.getId()) {
case R.id.button:
// Your click even code for all activities
break;
default:
break; }}
}

Use it the class A and B both as shown below: Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new MyClickListener());

Upvotes: 2

FThompson
FThompson

Reputation: 28687

You must pass an instance of an OnClickListener to button.setOnClickListener(..). Class A isn't implementing OnClickListener, so you must implement it in order for it to be an instance of an OnClickListener.

class A extends Activity implements OnClickListener {
    // instance variable, constructors, etc
    @Override
    public void onClick(View v) { // note onClick begins with lowercase
        // DO SOMETHING
    }
}

Upvotes: 1

Related Questions