2014-01-05 96 views
0

我有這樣的代碼:按鈕點擊收聽

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類。
但我不知道該怎麼做。

+0

問題解決了嗎? – Raghunandan

回答

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 { 
0

實施View.onClickListener和ònClick`以上方法你應該包括@Override表示法

2
  • 首先你必須把`final button button1 =(Button)findViewById(R.id.Button01); button1.setOnClickListener(this);

    final Button button2 =(Button)findViewById(R.id.Button02); button1.setOnClickListener(this);在onCreate()方法中使用' '。

  • 他們寫(實現OnClickListener後延伸活動),將要求實施方法單擊

,它會自動創建的onclick方法。在那裏讓你切換代碼。

希望它會起作用並幫助您解決錯誤。