Android - Different ways to "set" a listener on objects

4

Is there a different way ("syntax") to "set" a listener on an object in Android? For example, I only know this form:

    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            activity.onBackPressed(-1);             
        }
    });
    
asked by anonymous 04.02.2015 / 17:06

1 answer

2

You can also assign clickEvent to xml :

<Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="OK"
     android:onClick="onClick" /> 

In Activity implement a method called onClick that receives View :

public void onClick(View v) {
    activity.onBackPressed(-1);             
}

The name of the method can be any one, as long as it is the same as that in xml .

Another way is Activity to implement the interface OnClickListener :

public class Main extends Activity implements OnClickListener {

    Button button1;
    Button button2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button1 = (Button) this.findViewById(R.id.Button1);
        button1.setOnClickListener(this);

        button2 = (Button) this.findViewById(R.id.Button2);
        button2.setOnClickListener(this);
    }

    public void onClick(View v) {

        if((Button)v == button1{
            //O button1 foi clicado
        }
        if((Button)v == button2{
            //O button2 foi clicado
        }
    }
}
    
04.02.2015 / 17:12