ボタンイベントの作成
■一番簡単なのは.xmlに android:onClick=”onClick”を追加してjavaに public void onClick(View view){で設定する。
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="次画面"
android:id="@+id/button"
android:onClick="onClick"
android:layout_below="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:layout_marginTop="57dp" />
import android.view.View;
import android.content.Intent;
public class ActivityFirst extends ActionBarActivity {
public void onClick(View view){
switch (view.getId()){
case R.id.button:
Intent intent = new Intent(this, ActivitySecond.class);
startActivity(intent);
break;
}
■こっちはOnClickListener を用いる面倒な例。
ckage jp.andsys.android.dogagecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
public class MainActivity extends Activity implements
View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("life cycle", "onCreate()が呼ばれました。");
setContentView(R.layout.activity_main);
Button calcButton =
(Button) findViewById(R.id.button_calculate);
calcButton.setOnClickListener(this);
Button calcLargeButton =
(Button) findViewById(R.id.button_calculate_large);
calcLargeButton.setOnClickListener(this);
}
public void onClick(View v) {
EditText yearText = (EditText) findViewById(R.id.text_year);
int year = Integer.parseInt(yearText.getText().toString());
int humanAge = 0;
// どちらのボタンがおされたか取得します。
int id = v.getId();
switch (id) {
case R.id.button_calculate:
// 小型・中型犬の場合
switch (year) {
case 1:
humanAge = 17;
break;
case 2:
humanAge = 24;
break;
default:
humanAge = 24 + (year - 2) * 4;
break;
}
break;
case R.id.button_calculate_large:
// 大型犬の場合
switch (year) {
case 1:
humanAge = 12;
break;
default:
humanAge = 12 + (year - 1) * 7;
break;
}
}
Toast.makeText(this, "人の年齢に換算すると"
+ String.valueOf(humanAge)
+ "歳です", Toast.LENGTH_LONG).show();
}
@Override
protected void onRestart() {
super.onRestart();
Log.v("life cycle", "onRestart()が呼ばれました。");
}
@Override
protected void onStart() {
super.onStart();
Log.v("life cycle", "onStart()が呼ばれました。");
}
@Override
protected void onResume() {
super.onResume();
Log.v("life cycle", "onResume()が呼ばれました。");
}
@Override
protected void onPause() {
super.onPause();
Log.v("life cycle", "onPause()が呼ばれました。");
}
@Override
protected void onStop() {
super.onStop();
Log.v("life cycle", "onStop()が呼ばれました。");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.v("life cycle", "onDestroy()が呼ばれました。");
}
}
