繁体   English   中英

两种不同活动中的两种不同SwitchCompats

[英]Two different SwitchCompats in two different activities

我在2个不同的活动中有2个不同的SwithCompat,我想要实现的是,如果我在活动A中单击SwitchCompat,那么也会在Acitivity B中也单击SwitchCompat。 反之亦然。

我可以用以下代码实现吗:

aSwitch = findViewById(R.id.switchs);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
              //do something
                }
            }
        });

首先,当您通过通行证用于开放式第二活动通行证时

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

并在第二个活动中获得捆绑

boolean value = getIntent().getExtras().getBoolean(key);

根据布尔值,您可以更改打开和关闭

您可以将接口定义为活动一中的回调,用于活动二,如下所示:

    public class ActivityOne{ 

           private ICallback mICallback;
           private SwitchCompat mSwitchButton;

            public interface ICallback {

                void getData(boolean state);

            }

mSwitchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {

            mICallback.getData(isChecked);
        }
    });
    }

在TwoActivity中:

public class TwoActivity implements OneActivity.ICallback{

  @Override
    public void getData(boolean state) {

//YOU CAN USE IT HERE IN SECOND ACTIVITY

    }

}

也许您在第一个活动中遇到的回调为null,然后从第一个活动转到第二个活动时应该传递上下文。

暂无
暂无

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

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