如何使嵌套开关工作?

时间:2018-01-30 18:22:50

标签: java android nested switch-statement

我对Android开发完全陌生,我对嵌套开关有一些问题。对于开始,我想知道这是否可能。

以下是我的篮球比赛得分+统计计数器代码的一部分。 所以为了向你解释我想做什么 - 用户将按下按钮(播放器)然后应用程序禁用屏幕上的所有按钮,除了统计按钮(例如+ 1点,+ 2点,+ 1助手等) 问题是我无法让程序让我进入第二个开关。 我可以使用任何帮助, 谢谢

@Override
public void onClick(View view){

    switch (view.getId()){
        case R.id.player1_team1:
            ((Button) findViewById(R.id.player2_team1)).setEnabled(false);
            ((Button) findViewById(R.id.player3_team1)).setEnabled(false);
            ((Button) findViewById(R.id.player4_team1)).setEnabled(false);
            ((Button) findViewById(R.id.player5_team1)).setEnabled(false);
            ((Button) findViewById(R.id.player1_team2)).setEnabled(false);
            ((Button) findViewById(R.id.player2_team2)).setEnabled(false);
            ((Button) findViewById(R.id.player3_team2)).setEnabled(false);
            ((Button) findViewById(R.id.player4_team2)).setEnabled(false);
            ((Button) findViewById(R.id.player5_team2)).setEnabled(false);

            switch (view.getId()){
              case R.id.plus1p:

              thisGame.setName(getStrings(player1_team1));
              thisGame.setOnePointer(1);
              scoreTeam1 += 1;
              scoreCount1(1);
              Toast.makeText(view.getContext(), "+1 point " + getStrings(player1_team1), Toast.LENGTH_SHORT).show();
            break;

2 个答案:

答案 0 :(得分:0)

您在两个开关中都切换了相同的表达式:view.getId(),但case表达式不同。

因此,要进入第二个switch case(嵌入在第一个view.getId()中,R.id.player1_team1必须等于R.id.plus1p }和case在同一时间。我猜这些值不同,因此无法进入第二个switch的{​​{1}}。

答案 1 :(得分:0)

我看到你在这里使用按钮...看起来如果你点击一个,它就会禁用其他按钮。为什么不用RadioButtons实现RadioGroup呢?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/playerGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/playerOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true" />

        <RadioButton
            android:id="@+id/playerTwo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RadioGroup>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button" />

</LinearLayout>

如果添加10个RadioButtons,如果选择一个,则无法选择其他9个等。然后,您可以在每个按钮的onclick中实现点击。它比你想要做的好10倍。