创建按钮一旦按下声音播放C#Xamarin(Visual Studio)

时间:2017-11-12 18:12:29

标签: c# android button xamarin

。我有一个小问题,制作一个小应用程序。

每个按钮播放一个声音,我设法让一个按钮播放一个声音,但我无法弄清楚如何制作第二个按钮。有什么想法吗?

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Media;

namespace SoundApp
{
 [Activity(Label = "SoundApp", MainLauncher = true, Icon =      "@mipmap/icon")]
 public class MainActivity : Activity
 {
    MediaPlayer _player;
    Button playButton;
    Button playButton1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        void PlayButton_Click(object sender, System.EventArgs e)
        {
            _player = MediaPlayer.Create(this, Resource.Raw.mysound);

            playButton = FindViewById<Button>(SoundApp.Resource.Id.playButton);
            playButton.Click += PlayButton_Click;
        }



        void PlayButton1_Click(object sender, System.EventArgs e)
        {
            // Second Button
            _player = MediaPlayer.Create(this, Resource.Raw.A);

            playButton1 = FindViewById<Button>(SoundApp.Resource.Id.playButton1);
            playButton1.Click += PlayButton1_Click;
        }

      }
 }
}

1 个答案:

答案 0 :(得分:1)

正如@Jason所说,不会将事件处理程序分配给事件处理程序内的按钮。像这样修改你的代码:

public class MainActivity : Activity
{
    MediaPlayer _player;
    Button playButton;
    Button playButton1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        playButton = FindViewById<Button>(Resource.Id.playButton);
        playButton.Click += PlayButton_Click;

        playButton = FindViewById<Button>(Resource.Id.playButton1);
        playButton.Click += PlayButton1_Click;

        void PlayButton_Click(object sender, System.EventArgs e)
        {
            _player = MediaPlayer.Create(this, Resource.Raw.mysound);
            _player.Start();
        }

        void PlayButton1_Click(object sender, System.EventArgs e)
        {
            // Second Button
            _player = MediaPlayer.Create(this, Resource.Raw.A);
            _player.Start();
        }

    }
}