B
B
baddev2019-04-18 23:37:00
Java
baddev, 2019-04-18 23:37:00

Why does the method specified in OnClick not work when there is an OnClickListener?

There is a simple button with a method in OnClick written in xml, which works great.

<Button
        ...
        android:onClick="onAddButtonClick" />

But it's worth adding something like this in the java file
btnAdd.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            btnAdd.setBackgroundTintList(ColorStateList.valueOf(Color.BLUE));
                        }
                        else {
                            btnAdd.setBackgroundColor(Color.BLUE);
                        }
                        Toast.makeText(MainActivity.this, "Ok!", Toast.LENGTH_SHORT).show();
                    }
                }
        );

now, when clicked, only the new method works, and the one that is registered in OnClick does not work.
I just started studying development for android, so I don’t understand how correct this behavior is, I would be grateful if you tell me why this is happening

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-04-19
@baddev

This is the correct behaviour. As far as you can see, the method is called set OnClickListener. This means that there can be only one such listener. Inside the view, it is simply physically stored alone, and when you put it from the code, it overwrites the one put down from xml.
Such a wonderful API.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question