How to catch a click event on a button?

前端 未结 7 935
[愿得一人]
[愿得一人] 2020-12-05 04:28

.NET Developer here just getting started with Eclipse and Android.

Can someone show me in the simplest way possible, with the absolute fewest lines of code, how to D

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 05:21

    The absolutely best way: Just let your activity implement View.OnClickListener, and write your onClick method like this:

    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
        case R.id.button1:
            // your code for button1 here
            break;
        case R.id.button2:
            // your code for button2 here
            break;
        // even more buttons here
        }
    }
    

    Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick:

    That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.

提交回复
热议问题