ふわふわぷかぷか

最近はイラレとAeにはまってます。

ボタンを2つ作る。

ボタンのイベントはネットでたくさん見つかったけど、ボタンを2つにした場合にどうすればいいかが見つからない…。

色々試してみて一応うまく動いたけど、普通はどうやってやるんだろう?

 

今回は、前回の「押したな!」のアプリにボタンを1つ増やして、ボタン1を押すと「押したな!」が、ボタン2を押すと「押しちゃった♪」が表示されるアプリを作りました。

 

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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
   
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ボタン1" />
   
        <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ボタン2" />
     
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         />

</LinearLayout>

 

Activityはこんな感じです。

public class ●●●Activity extends Activity implements OnClickListener {
    TextView tv;
    Button button1,button2;

    /** 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.text);

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);}

    public void onClick(View v) {
        if (v == button1){
            tv.append("押したな!");}
       
        if (v == button2){
            tv.append("押しちゃった♪");}
        }}

ボタンなどを増やした場合、Button button1,button2; のようにコンマをつけて増やしていくみたいです。

私はこんがらがっちゃうので、名前とidは同じにしてみました(笑)

他に書き足した部分は、

button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);}

 と、

 if (v == button2){
    tv.append("押しちゃった♪");}

 です。

「if(v == ○○)」の〇〇の部分を変えると、ボタンが何個でも大丈夫みたい。

 

アプリを起動してみると、こうなります。

ボタン1を押すと「押したな!」が、ボタン2を押すと「押しちゃった♪」が表示されます。

f:id:fuwafuwapukapuka:20140209210141j:plain  → f:id:fuwafuwapukapuka:20140209210147j:plain

 

10日でおぼえるAndroidアプリ開発入門教室 第2版 AndroidSDK 4/3/2対応 (10日でおぼえるシリーズ)

10日でおぼえるAndroidアプリ開発入門教室 第2版 AndroidSDK 4/3/2対応 (10日でおぼえるシリーズ)