简体   繁体   English

当我打开和关闭它时,如何使labelSwitch做某事?

[英]How to make a labelSwitch do something when I turn it on and off?

When I press my switch so that it shows the "on" position, how do I actually make it do something, for example, link it to a method that sets the volume of a player to 0? 当我按下开关以使其显示在“ on”位置时,我实际上如何使其执行某些操作,例如,将其链接到将播放器的音量设置为0的方法? I'm guessing its Interface FieldChangeListener ? 我猜它的接口FieldChangeListener吗?

All my implementation occurs in the MainScreen class. 我所有的实现都发生在MainScreen类中。

Bitmap switch_left = Bitmap.getBitmapResource("switch_left.png");
Bitmap switch_right = Bitmap.getBitmapResource("switch_right.png");
Bitmap switch_left_focus = Bitmap.getBitmapResource("switch_left_focus.png");
Bitmap switch_right_focus = Bitmap.getBitmapResource("switch_right_focus.png");

LabeledSwitch silentSwitch = new LabeledSwitch(switch_left, switch_right, switch_left_focus, switch_right_focus, "on", "off", true );
JustifiedHorizontalFieldManager silent = new JustifiedHorizontalFieldManager( new LabelField( "Silent Mode" ), silentSwitch, false, USE_ALL_WIDTH );
silent.setPadding(5,5,5,5);
add(silent);

I imported a game demo called OpenGlSpriteDemo, and looked at how they implemetned the start button with field change listener, so I tried to do that for the Labeledswitch. 我导入了一个名为OpenGlSpriteDemo的游戏演示,并研究了它们如何通过字段更改侦听器实现“开始”按钮,因此我尝试为Labeledswitch做到这一点。 Am I heading in the right direction? 我朝着正确的方向前进吗?

LabeledSwitch silentSwitch = new LabeledSwitch(switch_left, switch_right, switch_left_focus, switch_right_focus, "on", "off", false );
silentSwitch.setChangeListener(this);

public void fieldChanged(Field arg0, int arg1) 
{
    //If user sets the switch to on, reduce the volume to 0, 
    // else if user sets the switch to false, change it back 
    // to the default volume    
}

在此处输入图片说明

Figured it out using a boolean flag to tell if its silent already or not, and used a get and set methods of the volume variable and pass it to: 使用布尔值标志判断它是否已经静音,然后使用volume变量的get和set方法将其传递给:

volume.setLevel(getVolume());       

and

boolean isSilent = false;

public void fieldChanged(Field field, int context) 
{
    if(!isSilent && field == silentSwitch)
    {
        setVolume(0);
        isSilent = true;
    }
    else if(field == silentSwitch && isSilent)
    {
        setVolume(20);
        isSilent = false;           
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM