본문 바로가기

Android/Simple Button Listener

Android Simple Button Click Listener example

안드로이드 버튼 클릭 이벤트를 처리하는 가장 간단한 예제


버튼이 선언된 레이아웃 파일에 onClick 속성을 추가하고 이벤트가 발생하면 호출될 메소드명을 속성의 값으로 지정한다

지정된 메소드는 Activity 클래스에 멤버 메소드로 선언해주면 되는데, public void 메소드명 (View v) 형식의 메소드 헤드를 가져야 한다


main_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >


    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />


    <Button

        android:id="@+id/button1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignLeft="@+id/textView1"

        android:layout_below="@+id/textView1"

        android:layout_marginTop="14dp"

        android:text="Button" 

        android:onClick="onClick"/>


</RelativeLayout>



MainActivity.java

package com.example.helloandroid;


import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.*;

import android.widget.TextView;


public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}


@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

public void onClick(View v) {

Log.i("버튼 이벤트", "버튼 눌림");

TextView tv  = (TextView)findViewById(R.id.textView1);

tv.setText("버튼 눌림");

}


}