Skip to content Skip to sidebar Skip to footer

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: Bu

Solution 1:

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.

publicclassMyClickListenerimplementsOnClickListener {
    @OverridepublicvoidonClick(View v) {
        mContext = v.getContext();

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

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

Solution 2:

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.

classAextendsActivityimplementsOnClickListener {
    // instance variable, constructors, etc@OverridepublicvoidonClick(View v) { // note onClick begins with lowercase// DO SOMETHING
    }
}

Post a Comment for "Setonclicklistener On Another Activity"