nedjelja, 31. kolovoza 2014.

How to create onClickListener for a button - android

This is one of the most common actions you will be doing if you develop something for Android or some other mobile platform.

Buttons are the usual way of interaction between the user and Android. As such they require proper visibility and functionality which will be implemented.

After you have instantiate your button as a variable in MainActivity:

Button buttonOsvjezi;

you need to assign a view to the button so that Android can know which button is being reference:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        buttonOsvjezi = (Button) findViewById(R.id.button_osvjezi);
        ...

Once your button has been referenced, you can assign some text over it or you can define its behavior. If you want to define 'what does this button do' when you press it, you do it by setting an OnClickListener like this:

buttonOsvjezi.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// Do something...
}

});

As you can see, after setting OnClickListener, that very listener has a built in method onClick which can be overridden. Using onClick method you can set what will your button do. It can, write a text, start a new activity, display an image, or any other function you like.

For example, this snippet will write a text in a textView which is somewhere on the screen:

TextView textview1;
buttonOsvjezi.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
textView1 = (TextView) findViewById(R.id.textView1); textView1("Hi, this text is displayed after clicking the button.");
}

});

Nema komentara:

Objavi komentar