반응형

Handling multiple buttons with one listener.

한 개의 리스너로 여러개의 버튼을 처리할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        findViewById(R.id.button1).setOnClickListener(myClick);
        findViewById(R.id.button2).setOnClickListener(myClick);
        findViewById(R.id.button3).setOnClickListener(myClick);
    }
 
    View.OnClickListener myClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.button1:
                    Toast.makeText(getApplicationContext(), "Button 1", Toast.LENGTH_SHORT).show();
                    break;
 
                case R.id.button2:
                    Toast.makeText(getApplicationContext(), "Button 2", Toast.LENGTH_SHORT).show();
                    break;
 
                case R.id.button3:
                    Toast.makeText(getApplicationContext(), "Button 3", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}



반응형
Posted by J-sean
: