๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’š ๊ฐœ๋ฐœ/์•ˆ๋“œ๋กœ์ด๋“œ

[์•ˆ๋“œ๋กœ์ด๋“œ : Kotlin] setOnClickListener ์‚ฌ์šฉ ๋ฐฉ๋ฒ•

by devshin.kr 2020. 12. 22.
728x90

์•ˆ๋“œ๋กœ์ด๋“œ์•ฑ์€ ์ž๋ฐ”์™€ ์ฝ”ํ‹€๋ฆฐ์œผ๋กœ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค..

์žฌํƒ๊ทผ๋ฌดํ•˜๋‹ˆ๊นŒ ํ‡ด๊ทผ ์‹œ๊ฐ„์ด 1์ดˆ๋ผ... ๊ทธ๋ƒฅ ์‹ฌ์‹ฌํ•ด์„œ ๋ˆ„์›Œ ์žˆ๋‹ค๊ฐ€... ์ฝ”ํ‹€๋ฆฐ ํ•ด ๋ณผ๊นŒ, ํ•ด์„œ ๊ธฐ๋ณธ ์˜ˆ์ œ๋ฅผ ๋งŒ๋“ค์–ด ๋ดค๋‹ค.

๋ญ.. ํ”„๋กœ์ ํŠธ ํ•˜๋‚˜ ์ƒˆ๋กœ ์ƒ์„ฑํ•ด์„œ ๋ณด๋‹ˆ๊นŒ build.gradle, AndroidManifest, activity_main์ด๋‚˜ libs์— ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ถ”๊ฐ€.. ๋“ฑ์€ ๊ธฐ์กด ์ž๋ฐ” ์ฝ”๋“œ๋กœ ์ž‘์„ฑํ•˜๋˜ ๊ฑฐ๋ž‘ ์ฐจ์ด๊ฐ€ ์—†๋‹ค. (์ด ๋ถ€๋ถ„์€ ์• ์ดˆ์— ์ฝ”ํ‹€๋ฆฐ ์ฝ”๋“œ๋กœ ์ž‘์„ฑ๋˜๋Š” ๋ถ€๋ถ„์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์—..)

 

 

์š”๊ตฌ ์‚ฌํ•ญ : Button์„ ํด๋ฆญํ•˜๋ฉด TextView์— hello world๊ฐ€ ์ถœ๋ ฅ๋˜๊ฒŒ ํ–ˆ๋‹ค.

 

์ฝ”๋“œ :

 

1) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <Button
        android:id="@+id/btn1"
        android:onClick="btnClick"
        android:text="๋ฒ„ํŠผ"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/text1"
        android:layout_below="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

 

2) MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btn = findViewById<Button>(R.id.btn1) as Button
        btn.setOnClickListener(View.OnClickListener {
            val textView = findViewById<TextView>(R.id.text1)
            textView.setText("hello world")
        })
    }
}

 

3) MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        Button btn = (Button)findViewById(R.id.btn1);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView textView = (TextView)findViewById(R.id.text1);
                textView.setText("hello world");
            }
        });
        
    }
}

 

 

2๋ฒˆ๊ณผ 3๋ฒˆ์€ ๋™์ผํ•œ ๋™์ž‘์„ ๊ฐ๊ฐ Java์™€ Kotlin ์–ธ์–ด๋กœ ์ž‘์„ฑํ•œ ์ฝ”๋“œ์ด๋‹ค.

๋น„๊ตํ•˜๋ฉฐ ๊ณต๋ถ€ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค..

 

 

 

๋Œ“๊ธ€