2016-09-14 80 views
0

我正在做Udacity的android初學者課程(即使我不是初學者編程),並決定稍微玩笑一下。Android - 讓按鈕在屏幕上顯示一個值,並正確播放聲音

我已經設法讓一個按鈕或者改變屏幕上的值(通過增加+1值)或播放聲音,但是當我混合使用時,按鈕只播放聲音,但不會添加數字/更新屏幕上的值,任何人都知道爲什麼?

我有三種方法; 1用於調用媒體播放器:

// This method calls mediaPlayer 
public void mediaPlayer (String sound, String id){ 
    Uri uriPlayer = Uri.parse("android.resource://" + getPackageName() + "/raw/" + sound); 
    final MediaPlayer mp = MediaPlayer.create(this, uriPlayer); 

    int playIdInt = getResources().getIdentifier(id, "id", getPackageName()); 
    Button play_button = (Button)this.findViewById(playIdInt); 
    play_button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      mp.start(); 
     } 
    }); 
} 
  • 有關屏幕

    /** 
    * This method displays the given quantity value on the screen. 
    */ 
    private void display(int number) { 
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view); 
    quantityTextView.setText("" + number); 
    
  • 顯示值對於添加1值的變量,調用顯示方法和媒體播放器的方法:

  • public void increment (View view){ 
        quantity = quantity + 1; 
        display(quantity); 
        mediaPlayer("mariocoin", "plus_button"); 
    } 
    

    編輯:不知道,如果需要的話,但這裏是按鈕的XML:

     <Button 
         android:id="@+id/plus_button" 
         android:layout_width="48dp" 
         android:layout_height="48dp" 
         android:onClick="increment" 
         android:text="+" /> 
    

    的事情是,當我打的按鈕,它第一次在屏幕上加1和顯示器,但沒有播放聲音。第二次和以後它只播放聲音。它不會將+1添加到變量中,也不會更改屏幕上的值。爲什麼以及如何解決這個問題?

    +0

    你從哪裏開始數量變量? –

    +0

    @Richard =我不確定我明白你的意思。該按鈕的XML代碼調用1.method:增量,它同時調用2.method:display和3.method:mediaPlayer – mrbTT

    +0

    數量變量是全局的,初始值爲0吧? –

    回答

    1

    看來你已經爲同一個按鈕定義了兩個ClickListeners。第一個調用增量方法,第二個調用內置媒體播放器方法。該聽衆不是必需的。

    //Somewhere in oncreate .. Not required if xml has onclick specified 
    Button play_button = (Button)this.findViewById(playIdInt); 
    play_button.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 
         increment(); 
        } 
    }); 
    
    
    public void increment (View view){ 
         quantity = quantity + 1; 
         display(quantity); 
         mediaPlayer("mariocoin", "plus_button"); 
    } 
    
    // This method calls mediaPlayer 
    public void mediaPlayer (String sound, String id){ 
          Uri uriPlayer = Uri.parse("android.resource://" + getPackageName() + "/raw/" + sound); 
          final MediaPlayer mp = MediaPlayer.create(this, uriPlayer); 
          mp.start(); 
         } 
    
    +0

    這就是它,非常感謝你!只是另一個問題:所以這是在onCreate內創建play_button的最佳做法?另外,我沒有在onCreate方法中添加「public void onClick(View v)」這一行,這是否有必要? – mrbTT

    +1

    閱讀本文http://stackoverflow.com/questions/21319996/android-onclick-in-xml-vs-onclicklistener –