Programming$/Android

onClickListener implements로 구현하기

ch4rli3kop 2020. 4. 14. 04:01
반응형

onClickListener implements로 구현하기


Anonymous class 이용해서 구현하기

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       Button btn1 = findViewById(R.id.button1);
       btn1.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Toast.makeText(getApplicationContext(),"AAAAAAAAAAAAAAAAAAAAAAAAA", Toast.LENGTH_SHORT).show();
          }
      });

       Button btn2 = findViewById(R.id.button2);
       btn2.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent myintent = new Intent(MainActivity.this, Main2Activity.class);
               myintent.putExtra("QWER", "HI Hello oooooolll~~~!");
               startActivity(myintent);
          }
      });
  }


Implements 이용해서 구현하기

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       Button btn1 = findViewById(R.id.button1);
       btn1.setOnClickListener(MainActivity.this);

       Button btn2 = findViewById(R.id.button2);
       btn2.setOnClickListener(MainActivity.this);
  }

   @Override
   public void onClick(View view) {

       switch(view.getId()){
           case R.id.button1:
               Toast.makeText(getApplicationContext(),"AAAAAAAAAAAAAAAAAAAAAAAAA", Toast.LENGTH_SHORT).show();
               break;
           case R.id.button2:
               Intent myintent = new Intent(MainActivity.this, Main2Activity.class);
               myintent.putExtra("QWER", "HI Hello oooooolll~~~!");
               startActivity(myintent);
               break;
      }
  }
}


반응형

'Programming$ > Android' 카테고리의 다른 글

[Android] 외부 라이브러리 사용하기  (0) 2021.10.04
glide (feat. custom dialog)  (0) 2020.06.24
JNI function symbol 제거하기  (0) 2020.06.12
Intent로 Activity 간 데이터 교환  (0) 2020.04.14