0

I have a Fragment which has a button. When creating a Fragment, I want to get a UiSettings instance from the fragment and change whether the button should be shown. You can get the idea looking here. So my code is:

class MyFragment extends Fragment{
    private Button button;
    private UiSettings settings;

    public getUiSettings(){
        return settings;
    }
}

class UiSettings{
    private boolean showButton = true;
    //setters and getters go here
}

My question is how do I trigger button visibility depending on UiSettings, and how do I connect button visibility state to the changes in UiSettings?

JJJ
  • 32,902
  • 20
  • 89
  • 102

1 Answers1

1

I would override onResume() in your Fragment and there grab the UiSettings instance and apply the value to the function with something like

button.setVisibility(uiSettings.showButton ? View.VISIBLE : View.GONE);

So in total, you would add to your code

@Override
public void onResume() {
    super.onResume();
    button.setVisibility(uiSettings.showButton ? View.VISIBLE : View.GONE);
}

It might also be a good idea to make UiSettings a class outside your Fragment's class, and then apply a public setter to the showButton variable, and in that setter change the visibility of the Fragment's button via a some interface that you'd create (essentially data-binding the two).

The interface might look something like

public interface Binding {
    dataChanged();
}

Then UiSettings

public class UiSettings {
    public Binding binder;
    private boolean showButton;

    public void setShowButton(boolean showButton) {
        this.showButton = showButton;
        if (binder != null) {
            binder.dataChanged();
        }
    }

    public boolean getShowButton() {
        return showButton;
    }
}

And your fragment would then implement Binding and have added to it

@Override
public void dataChanged() {
    button.setVisibility(uiSettings.getShowButton() ? View.VISIBLE : View.GONE);
}
bclymer
  • 6,679
  • 2
  • 27
  • 36