【问题标题】:How to compare two button values in Android如何比较Android中的两个按钮值
【发布时间】:2016-04-11 18:43:49
【问题描述】:

第一次在这里发帖,如果我做错了什么,请指教:)

我正在为大学项目构建一个应用程序。

我拥有的是 Android Studio 中的两个按钮。第一个按钮创建一个随机数,第二个按钮我需要将它与按钮一个进行比较,如果它们匹配则播放一些音频。

这是随机数按钮的代码..

public void random(View view) {
int rando = (int) (Math.random()*6);
if(rando == 1){
        play_s.start();
    }else if (rando == 2){
        play_t.start();
    }else if (rando == 3){
        play_p.start();
    }else if (rando == 4){
        play_i.start();
    }else if (rando == 5){
        play_n.start();
    }else {
        play_a.start();
    }

这是两个按钮的代码

 <Button
    android:id="@+id/button_s"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="@string/button_s"
    android:padding="16dp"
    android:textColor="@color/White"
    android:background="@layout/nice_button"
    android:textSize="50sp"
    android:layout_below="@+id/imageBtnBack"
    android:layout_centerHorizontal="true" />

<Button
    android:id="@+id/button3"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:onClick="random"
    android:text="Press for letter"
    android:textColor="@color/White"
    android:background="@layout/nice_button"
    android:textSize="20sp"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/button_i"
    android:layout_alignEnd="@+id/button_i" />

所以,我的问题是,如果第二个按钮与第一个按钮匹配,我该如何播放一些音频?

提前谢谢..

【问题讨论】:

  • 是什么决定了按钮是否“匹配”?上面显示的文字?
  • 这是我遇到困难的部分。我怎样才能让他们匹配? button_s 应该有这个 android:text="s"
  • 我不知道你在问什么。按钮有setTextgetText 方法
  • 好的,所以。当 button3 被按下时,用户被要求选择字母 S,当用户选择 button_s 时,会播放音频来表示正确或失败。
  • 好的,那么你在实现它时遇到了什么问题?你的问题只显示了一个random 方法,看起来它会start() 一些随机对象。

标签: android android-button


【解决方案1】:

您需要一个所有按钮的列表,例如List&lt;Button&gt; allButtons;,然后您可以稍后获取它们并像这样比较它们上显示的文本。

public void random(View view) {
    Button clicked = (Button) view;
    String clickedTxt = clicked.getText();

    int rando = (int) (Math.random()*6);
    Button randoButton = allButtons.get(rando);

    if(rando == 1 && clickedTxt.equals("s")) {
        play_s.start();
    }

}

如果您想将您单击的按钮与随机按钮的内容进行比较,那么您可能需要TextUtils.equals(clicked.getText(), randoButton.getText())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多