1

I have a compound view CheckboxesView, where I have some checkboxes:

CheckboxesView

checkboxes_view_layout:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android...>
    <CheckBox
       ...
    />
    <CheckBox
       ...
    />
    ...
</androidx.constraintlayout.widget.ConstraintLayout>

In the respective class for this view, I have the following init

init {
    View.inflate(context, R.layout.checkboxes_view_layout, this)

    if(valueExists()) {
        hideCheckboxes()
    }
}

I use this CheckboxesView in an MyActivity, which obviosuly has its own Layout my_activity_layout

MyActivity

my_activity_layout:

<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android=.../>
    ....

    <CheckboxesView
                    android:id="@+id/checkboxesView"
                    .../>

    ....
</androidx.constraintlayout.widget.ConstraintLayout>

CheckboxesView.valueExists() checks for some value that is saved in preferences and if valueExists returns false, I make checkboxesView invisible by calling CheckboxesView.hideCheckboxes() as seen in the code above.

In the app, this works perfectly. The preferences value is checked and if necessary the checkboxes are hidden. However, I dont want this to happen when I look at the preview of my_activity_layout. Obviously the preview of my_activity_layout calls CheckboxesView.init which checks for the nonexisting preference which causes the view to never be visible in the preview.


Is there a way for me to have a piece of code that is not called for a layout preview? For example:

init {
    View.inflate(context, R.layout.checkboxes_view_layout, this)

    if(System.NotAPreview()) {    
        if(valueExists()) {
            hideCheckboxes()
        }
    }
}

For those of you who are somewhat familiar with C# and VisualStudio, I basically want to do something in the lines of detecting design mode

Benjamin Basmaci
  • 1,837
  • 1
  • 23
  • 39

1 Answers1

1

Try using the following:

View.isInEditMode()

https://developer.android.com/reference/android/view/View#isInEditMode()

A view is usually in edit mode when displayed within a developer tool.

If the view is drawn by a visual user interface builder this method should return true.

In your specific case:

if (!View.isInEditMode()) {
    if (valueExists()) {
        hideCheckboxes()
    } 
}
jeprubio
  • 16,152
  • 5
  • 40
  • 51