ボタンのイベント処理 —
基本的なことですが、ボタンを押した時のイベント処理について記述してみました。
ボタンを押したときに、「ボタンが押された」というメッセージを表示します。
まずは、空のXMLにボタンの記述を行います。
onClickのプロパティで指定してやることよって、ボタンが押された時にそのメソッドに飛びます。
下記の例では「onTestClick」という任意の名前のメソッドを指定しています。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン"
android:onClick="onTestClick"
/>
</LinearLayout>
次にコード側の実装です。
XMLで記述した呼び先のメソッド名「onTestClick」をこちらでも記述します。
public class TestMainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onTestClick(View view) {
Toast.makeText(this, "ボタンが押された", Toast.LENGTH_LONG).show();
}
}
これらによって、ボタンが押された時に「ボタンが押された」とメッセージが表示される機能ができました。
尚、タイプミスなどで「onTestClick」というメソッド名が間違っていると、次の例のようなエラーで落ちることがあります。
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find a method onTestClick(View) in the activity class com.example.test.TestMainActivity for onClick handler on view class android.widget.Button
古いバージョンのProGuardで難読化すると、落ちるケースもありましたが、最近のものは大丈夫みたいですね。
Categorised as: 画面関連

コメントを残す