【问题标题】:Android Multiple switches安卓多开关
【发布时间】:2015-08-20 14:09:04
【问题描述】:

我在 Android 中的 switch-struktur 遇到了一些问题。

我想创建 3 个开关,它们能够改变我的相对布局的背景颜色。

现在我的重点是,我的开关可以改变背景颜色, 但即使 3 个中的 1 个在工作,其他的都没有。

我怎样才能让它们全部工作? 目前我使用 if-struktures:

@Override
    //Teil2
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                //Action für Switches

    RelativeLayout lay1 = (RelativeLayout) findViewById(R.id.lay1);


    if (switch1.isChecked()){                                                                   //isChecked() => Wenn "an"

        TextView label2 = (TextView)findViewById(R.id.label2);                                  //Label label2 auswählen
        label2.setText("On");
                                                                                                //Layout aus activity_main.xml, verknüpft über die id. (Wenn in main "Relative layout", dann hier auch
        lay1.setBackgroundColor(Color.parseColor("#ff95e1ff"));                                 //Farbe muss geparst werden, damit Hexadezimal Zahlen gehen

    }else{
        TextView label2 = (TextView)findViewById(R.id.label2);
        label2.setText("Off");

        lay1.setBackgroundColor(Color.WHITE);
    }


    if (switch2.isChecked()){

        TextView label3 = (TextView)findViewById(R.id.label3);
        label3.setText("On");

        lay1.setBackgroundColor(Color.RED);

    }else{
        TextView label3 = (TextView)findViewById(R.id.label3);
        label3.setText("Off");

        lay1.setBackgroundColor(Color.WHITE);
    }


    if (switch3.isChecked()){

        TextView label4 = (TextView)findViewById(R.id.label4);
        label4.setText("On");

        lay1.setBackgroundColor(Color.GREEN);

    }else{
        TextView label4 = (TextView)findViewById(R.id.label4);
        label4.setText("Off");

        lay1.setBackgroundColor(Color.WHITE);
    }


}

感谢您的帮助!

【问题讨论】:

    标签: java android if-statement switch-statement


    【解决方案1】:

    也许当你使用开关时你忘记了

    休息;

    声明。这将停止 case 块中的流程。 请通过开关传递您的代码。

    【讨论】:

      【解决方案2】:

      Switch-Case 不会帮助或简化您的代码,因为您的变量状态仅包含 2 个选项 true 或 false,

      等效的 switch 语句是(对于 switch1)

      switch(switch1.isChecked()){
        case true:
          TextView label2 = (TextView)findViewById(R.id.label2);                                  
          label2.setText("On");
          lay1.setBackgroundColor(Color.parseColor("#ff95e1ff"));  
          break;
      
        case false: 
          TextView label2 = (TextView)findViewById(R.id.label2);
          label2.setText("Off");
          lay1.setBackgroundColor(Color.WHITE);
          break;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多