无法从外部类更改我的片段变量的值

问题描述 投票:0回答:1

我正在使用fragments,但无法从外部类访问其变量。

当前,我有一个片段fragmentView,它的设置为button。每当按下它时,都会显示一个UI元素以定义不同的设置。我复制了我拥有的代码:

片段

 public static Boolean show = false;


 private void initSettingsPanel() {
    m_settingsBtn = (ImageButton) m_activity.findViewById(R.id.settingButton);

    /* click settings panel button to open or close setting panel. */
    m_settingsBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            m_settingsLayout = (LinearLayout) m_activity.findViewById(R.id.settingsPanelLayout);
            if (m_settingsLayout.getVisibility() == View.GONE) {
                m_settingsLayout.setVisibility(View.VISIBLE);
                if (m_settingsPanel == null) {
                    m_settingsPanel = new SettingsPanel(m_activity, show); //HERE I CALL THE EXTERNAL CLASS
                }
            } else {
                m_settingsLayout.setVisibility(View.GONE);
            }
        }
    });

}

SettingsPanel

    private Activity m_activity;
    private static Boolean p_show;
    private Switch p_switch;


    public SettingsPanel(Activity activity, Boolean show
) {
      p_show = show;
      m_activity = activity;
      initUIElements(); // Init switch
}

    private void initUIElements() {

      p_switch = (Switch) m_activity.findViewById(R.id.showSwitch);
      setUIListeners();
}

    private void setUIListeners() {

      p_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            p_show = isChecked;
        }
    });
  }
  }

当前正在发生的事情是,当我激活开关时,我更改了Pannel的变量的值,但它不影响片段。为什么?还有其他方法可以更改其变量的值,而不发送给每个变量SettingPanel吗?这至少是正确的方法吗?

android variables fragment
1个回答
0
投票

最后,我创建了一个abstract class以将getset变量:

ShowVar

public abstract class ShowVar {
  static private Boolean show = false;
  public Boolean getShow() {
    return show;
  } 

  public void setShow(Boolean value) {
    this.show = value;
  } 
}

从我的SettingPanel中,我有一个实例ShowVar每次都要设置变量的新值并更改switch

SettingsPanel

public class SettingsPanel {
public ShowVar showVar = new ShowVar() {
        @Override
        public void set_Show(Boolean show) {
            super.setShow(show);
        }

    };
}

并且从我的片段中,我可以使用变量m_settingsPanel访问值

片段

m_settingsPanel.showVar.getShow()
© www.soinside.com 2019 - 2024. All rights reserved.