Android - Different ways of "setar" a system in objects

Asked

Viewed 516 times

5

Is there a different way (Syntax) to "set" a Switch on an object on Android ? For example, I only know this way:

    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            activity.onBackPressed(-1);             
        }
    });

1 answer

2


It is also possible to assign the clickEvent in the xml:

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

In the Activity implement a method called onClick who receives a View:

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

The name of the method may be any one, provided that it is equal to that indicated in xml.

Another way is the very Activity 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
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.