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

时间:2018-12-06 06:19:32

标签: java android android-layout android-activity

我在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
                }
            }
        });

2 个答案:

答案 0 :(得分:1)

首先,当您通过捆绑销售商品进行开放第二次活动捆绑销售商品

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

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

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

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

答案 1 :(得分:0)

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

    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,然后从第一个活动转到第二个活动时应该传递上下文。

相关问题