在一些设备上,充气约束布局会导致崩溃

4

我有一个XML布局,在某些设备上运行正常,但在其他设备上膨胀时崩溃(仅显示部分XML代码):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout_record_audio"
android:minWidth="@android:dimen/dialog_min_width_major"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>

在某些设备上,布局的填充很好,但在其他设备上会导致InflateException

我在我的xml文件中找到了罪魁祸首:

<!-- Causes InflateException on some devices: 
     android:minWidth="@android:dimen/dialog_min_width_major"  -->

很遗憾,删除导致InflateException的行后,android:layout_height="wrap_content"不再起作用。 layout_height始终呈现为设置为"match_parent"。有什么想法以及如何解决?
为了更清晰地说明,以下是我调用对话框的方式:
fun showRecordAudioDialog(view: View, categoryId: String, detailId: String) {
    val dialog = RecordAudioDialogFragment.newInstance(categoryId, detailId)
    dialog.show(this@DetailsActivity.supportFragmentManager, "RecordAudioDialog")
}

在我的RecordAudioDialogFragment中:
    // Use the Builder class for convenient dialog construction
    val builder = AlertDialog.Builder(activity, style.CustomTheme_Dialog)

    val inflater = activity.layoutInflater
    val rootView = inflater.inflate(layout.dialog_record_audio, null)

@AIK 包括 android:minWidth="@android:dimen/dialog_min_width_major" 就会崩溃!回到原点! - CEO tech4lifeapps
@Cheticamp 你可能是对的,但问题似乎与API版本无关。最新的设备在API 26(Android O)上运行时会崩溃,但在我运行Android M的平板电脑上不会崩溃。 - CEO tech4lifeapps
1
一个简单的测试方法是定义自己的尺寸值,以查看是否解决了崩溃问题。 - Cheticamp
我应该更仔细地阅读你的问题。所以,你删除了麻烦的那一行,但是(对话框?)的高度变成了全屏。你能否更具体地说明对话框是如何创建的,并可能提供其XML代码? - Cheticamp
@Cheticamp,我编辑了我的问题(希望)澄清我实际在做什么。 - CEO tech4lifeapps
显示剩余3条评论
1个回答

2
由于某种奇怪的原因,如果未设置android:minWidth,则android:layout_height无法正常工作。
因此,在dimens.xml中,我们需要添加一行类似以下的代码:<dimen name="dialog_min_with">500dp</dimen> 然后在mylayout.xml文件中添加android:minWidth="@dimen/dialog_min_with"
现在,布局文件的头部看起来是这样的:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constraintLayout_record_audio"
android:minWidth="@dimen/dialog_min_with"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接