bodhisattwa
bodhisattwa

Reputation: 27

Function calling from custom OnClickListener

I've Main_Activity.class file. There I am defining a custom function myFunction() . In this function I want to call an externally defined custom OnClickListener which will call the function recursively.

In Main_Activity the button is defined as

private Button button;
.
.
button = (Button)findViewById(R.id.button);
.
.

My myFunction() is defined inside Main_Activity.class. And inside this function the OnClickListener for button is defined. From this OnClickListener, I can easily call the myFunction().

private void myFunction(){
  button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                                 myFunction();
            }
        });
}

But I want to define a custom MyClickListenerClass for button and call the myFunction() from that external class.

How can it be possible??

Upvotes: 0

Views: 1914

Answers (1)

dd619
dd619

Reputation: 6170

try this,

Activity:

 public class Main_Activity extends Activity
{

    Button button;
    MainActivity act;
    MyClickListener listener;

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

            button = (Button) findViewById(R.id.button1);
            listener = new MyClickListener(this);
            myFunction();
        }

    public void myFunction()
        {
            button.setOnClickListener(listener);
            Log.i("Fun clicked from", "sdfnd");
        }
}

and class:

public class MyClickListener implements OnClickListener 
{
    MainActivity act;
      public MyClickListener(MainActivity act) { 
         this.act=act;

      }
    @Override
    public void onClick(View v)
        {
            act.myFunction();

        } 
}

Upvotes: 3

Related Questions