Androidアプリ入門 No.14 Buttonで音を鳴らす。
Button
音を鳴らす
Buttonとは直接関係がないが、通常のAndroidアプリの場合Buttonを押した場合やCheckBoxをクリックした場合に「ピッ」と音が鳴る。その実装を確認する。まず、main.xmlを示す。
<?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" android:background="#ffffff" > <Button android:id="@+id/soundButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="音が鳴る" android:textColor="#000" android:textSize="16sp" android:soundEffectsEnabled="true" /> <Button android:id="@+id/noSoundButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="音が鳴らない" android:textColor="#000" android:textSize="16sp" android:soundEffectsEnabled="false" /> </LinearLayout>
次に、MainActivity.javaを示す。
package sample.at; import android.app.Activity; import android.os.Bundle; import android.view.SoundEffectConstants; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button soundButton = (Button) findViewById(R.id.soundButton); soundButton.setOnClickListener(ocl); Button noSoundButton = (Button) findViewById(R.id.noSoundButton); noSoundButton.setOnClickListener(ocl); } private OnClickListener ocl = new OnClickListener() { @Override public void onClick(View v) { v.playSoundEffect(SoundEffectConstants.CLICK); } }; }
実行画面は以下。しかし、エミュレータでサウンドの確認ができなかった。実機(GALAXY S)では「音が鳴る」ボタンで音が鳴り、「音が鳴らない」ボタンでは音が鳴らなかった。