是否只有在授予特定权限的情况下才能将 View 添加到布局?
我正在使用一个名为 QRCodeReaderView 的二维码阅读器库.我在布局中使用 com.dlazaro66.qrcodereaderview.QRCodeReaderView
。
在 Android M 及更高版本上,如果 View 位于布局中,除非用户接受许可,否则应用程序会崩溃。
是否有可能在加载布局时我可以进行检查并决定仅在授予权限的情况下包含此 View
最佳答案
@CherryPerry 回答的一些补充:
无需创建两个不同的布局。您可以将 ViewStub
和 QRCodeReaderView
放入您的布局中,并仅在获得许可后调用 inflate
:
if (permissionGranted()) {
qrReaderStub.inflate();
}
参见 more about ViewStub .
示例:
<!-- 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();
}
}
关于android - 我可以检查android布局中授予的权限吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37674467/