안드로이드 앱 - 버튼 클릭 이벤트 처리 두 가지 방법

버튼 클릭 이벤트 처리 두 가지
1. Button의 setOnClickListener() 사용
2. Button의 onClick 속성에 method 지정하기

<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button1_text"/> <!-- 1. -->
<Button
android:id="@+id/button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button2_text"
android:onClick="button2_onclick"/> <!-- 2. -->
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.app.ActionBar actionbar = getSupportActionBar();
if (actionbar != null) {
actionbar.setDisplayShowHomeEnabled(true);
actionbar.setIcon(R.mipmap.ic_launcher);
}
Button button1 = (Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() { // 1.
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), R.string.button_press_msg,
Toast.LENGTH_SHORT).show();
}
});
}
public void button2_onclick(View v) { // 2.
Toast.makeText(getApplicationContext(), R.string.button_press_msg,
Toast.LENGTH_SHORT).show();
}
}