Android - 让按钮在屏幕上显示一个值,并正确播放声音

问题描述:

我正在做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(); 
     } 
    }); 
} 
  1. 有关屏幕

    /** 
    * 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); 
    
  2. 显示值对于添加1值的变量,调用显示方法和媒体播放器的方法:

  3. 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吧? –

看来你已经为同一个按钮定义了两个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://*.com/questions/21319996/android-onclick-in-xml-vs-onclicklistener –