ボタンを押したら何かが起こるようにする。
ボタンを押したら何かが起こるようにするには
(↑これを「イベント」と呼ぶっぽい。)
Activityに、implements OnClickListenerを書かないといけないみたい
public class ●●●Activity extends Activity implements OnClickListener {
その下に、Button name; を書く。
この「name」は、たぶん適当に名付けていいのかな。
あとは、
name = (Button)findViewById(R.id.button1); name.setOnClickListener(this);
idの「button1」は、layoutのxmlの「android:id="@+id/〇〇"」の〇〇の部分。
全部つなげると、
public class ●●●Activity extends Activity implements OnClickListener { /** Called when the activity is first created. */ button name; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name = (Button)findViewById(R.id.button1); name.setOnClickListener(this);
ここまででアプリに、ボタンを作ったよ、こうやって名前をつけて、レイアウトのあの場所にあるよ、だからクリックしたら反応してね♪って教えてあげているのだと思う。
次は、反応の内容を教えてあげる。
ボタンを押すと、「押したな!」と表示するアプリを作ってみる。
表示する場所がほしいので、ボタンの他にテキストビューも使う。
今回増やす部分は、
public void onClick(View v) {
if (v == button) {
tv.append("押したな!");
}}
ifは英語で「もし」だから、きっと 、
もしbuttonを押したらtvに「押したな!」をappendしてね。って感じかな。
appendは追加するという意味。appendを変えれたらいろんなことができるんだろうなぁ。
全部表示すると、まず、main.xmlは、
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン" />
<TextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
次に、Activityは
public class HelloandroidActivity extends Activity implements OnClickListener{
TextView tv;
Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text1);
button = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);} public void onClick(View v) {
if (v == button){
tv.append("押したな!");
}}}
これでボタンを押すと、「押したな!」がどんどん表示される。
右は3回ボタンを押したところ。
→
ちなみに、「append」を「setText」に変えると、追加されずに、1度だけ表示される。