按钮单击侦听器

时间:2014-01-05 17:55:42

标签: java android

我有这段代码:

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    MediaPlayer sound1, sound2;
    sound1 = MediaPlayer.create(this, R.raw.cows);
    sound2 = MediaPlayer.create(this, R.raw.sheep);

    final Button button1 = (Button) findViewById(R.id.Button01);
    button1.setOnClickListener(this);

    final Button button2 = (Button) findViewById(R.id.Button02);
    button1.setOnClickListener(this);

    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.Button01:
                sound1.start();
                break;
            case R.id.Button02:
                sound2.start();
                break;
        }
    }

    protected void onDestroy() {
        sound1.release();
        sound2.release();
        super.onDestroy();
    }
}

我发出警告说按钮和视图不正确 但是,我不明白上述代码有什么问题 我似乎需要实例化按钮类和View类 但我不知道该怎么做。

3 个答案:

答案 0 :(得分:3)

这应该在方法

sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);


final Button button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);

final Button button2 = (Button) findViewById(R.id.Button02);
button1.setOnClickListener(this); // should be button2

您可以在onCreate

中初始化您的观看次数
Button button1,button2;
MediaPlayer sound1,sound2;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);

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

然后

public class MainActivity extends Activity implements onClickListener {

答案 1 :(得分:2)

  • 首先你必须把`final Button button1 =(Button)findViewById(R.id.Button01); button1.setOnClickListener(本);

    final Button button2 =(Button)findViewById(R.id.Button02); button1.setOnClickListener(本); `in onCreate()方法。

  • 他们写的(在扩展Activity之后实现OnClickListener)将要求实现方法点击

这将自动创建onclick方法。在那里让你切换代码。

希望它会起作用并帮助您解决错误。

答案 2 :(得分:0)

实施View.onClickListener并在ònClick`方法上方,您应该包含@Override表示法

相关问题