Search code examples
androidvisibilityandroid-camerax

Unable to change visibility of view other than onCreate method


I am unable to change the view visibility inside other function rather than onCreate method. Its working only at time of onCreate is called.

public class CameraXActivity extends AppCompatActivity {
    ...
    public Group fipGroup;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camerax_layout); // Created xml using constraintLayout.

        //intial setup
        fipGroup = (Group)findViewById(R.id.fip_group);
        startCamera();

        //hideFipGroup(); <<--- This is working
    }

    private void hideFipGroup() {
        Log.d(TAG, "=== hideFipGroup ===");
        fipGroup.setVisibility(View.INVISIBLE);
    }

    private void startCamera() {
        CameraX.unbindAll();
        preview = setPreview(); 
        imageAnalysis = setImageAnalysis();

        //bind to lifecycle:
        CameraX.bindToLifecycle(this, preview , imageAnalysis);
        preview.enableTorch(true);
    }

    private ImageAnalysis setImageAnalysis() {
        hideFipGroup() // This is working
        imageAnalysis.setAnalyzer(
                new ImageAnalysis.Analyzer() {
                    @Override
                    public void analyze(ImageProxy image, int rotationDegrees) {
                        hideFipGroup() // Exactly, Failed at this place.
                    }
                }
        )
    }

}

Edit Update:

It's failing to update on the analyze method of imageAnalysis. Just to test, called toast message which is showing on the UI. But am not able to control the UI.

private void raiseToast(String msg) {

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 500);
                toast.show();
            }
        });
    }

Solution

  • The problem is with Group visibility on constraint Layout.

    private void setGroupVisiblity(Group group, int visibility) {
       group.setVisibility(visibility);
       group.requestLayout();
    }
    

    or manually turn off each views in the group:

    private void setGroupVisibility(ConstraintLayout layout, Group group, Integer visibility) {
         int[] refIds = group.getReferencedIds();
         for (int id : refIds) {
              layout.findViewById(id).setVisibility(visibility);
         }
    }
    

    or upgrade to ConstraintLayout version 2.0.0 beta 6

    source: Can't set visibility on constraint group