dmSherazi dmSherazi - 6 months ago 23
Android Question

Can I check granted permissions in android layout

is it possible to add a view to layout only if a certain permission is granted?

I am using a QR Code reader library called QRCodeReaderView. I am using the

com.dlazaro66.qrcodereaderview.QRCodeReaderView
in my layout.

On Android M and above it would crash the app if the view is in the layout unless the user accepts the permission.

Is it possible that when loading the layout I can make a check and decide to include this view only if permission is granted

Answer

Some supplement to @CherryPerry's answer:
There is no need for create two different layouts. You can put ViewStub with QRCodeReaderView into your layout, and call inflate only if permission granted:

if (permissionGranted()) {
    qrReaderStub.inflate();
}

see more about ViewStub.


Sample:

<!-- qr_reader.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<com.dlazaro66.qrcodereaderview.QRCodeReaderView
    android:id="@+id/qr_reader"
    android:layout_width="100dp"
    android:layout_height="100dp" />


<!-- your activity or fragment -->
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ViewStub 
           android:id="@+id/qr_stub"
           android:layout="@layout/qr_reader"
           android:layout_width="100dp"
           android:layout_height="100dp" />

</FrameLayout>


//your activity class
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
        ViewStub.class.cast(findViewById(R.id.qr_stub)).inflate();
    }
}