java - 按钮点击监听器

标签 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 不正确。
但是,我不明白上面的代码有什么问题。
看来我需要实例化按钮类和 View 类。
但我不知道该怎么做。

最佳答案

这应该在方法内部

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中初始化 View

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 {

关于java - 按钮点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20937052/

相关文章:

java - java+python+ruby的持续构建框架?

java - 如何使用 Spring、Hibernate、MySQL ISAM 进行事务处理?

java - RecyclerView 项目选择抛出错误

android:layout_alignParentBottom 在运行时不工作

android - 发送不 protected 广播 com.motorola.motocare.INTENT_TRIGGER java.lang.Throwable

java - 在公共(public)表保存多个表的元数据的情况下使用 Hibernate

java - 从适配器获取链接到 Activity ,然后在外部播放器中打开链接?

java - getAsync ("key").get(timeout, sec) 不等待,返回 null

Android 蓝牙连接问题

android - 无法解决 ':app@debug/compileClasspath' 的依赖关系