Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

android- multi onClick listener in one button

I have made a custom component like Mybutton.java and I have set an onclick listener in Mybutton.java.

Now, in my new activity, I have to call a Mybutton and add content in onclick listener.

However, if I use OnClickListener mClickListener = new OnClickListener(){...... it will replace the old content. I hope it can do the old and new listener together.

I have searched for some information, found out i can implement this method. After many attempts, I'm still getting errors.

Can anyone give me a simple example that i can learn to modify it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think there's an API in the Android API that allows multiple onClick listeners. You'd need some custom class that handles a single onClick() and pass in handlers for it to call. Something like this:

private class CompositeOnClickListener implements View.OnClickListener{
    List<View.OnClickListener> listeners;

    public CompositeOnClickListener(){
        listeners = new ArrayList<View.OnClickListener>();
    }

    public void addOnClickListener(View.OnClickListener listener){
        listeners.add(listener);
    }

    @Override
    public void onClick(View v){
       for(View.OnClickListener listener : listeners){
          listener.onClick(v);
       }
    }
}

When your setting your buttons, do:

CompositeOnClickListener groupListener = new CompositeOnClickListener();
myButton.setOnClickListener(groupListener);

Then, whenever you want to add another listener, just call

groupListener.addOnClickListener(new View.OnClickListener(){
   @Override
   public void onClick(View v){
      **** Custom implementation ****
   }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...