relativeLayout.setBackground(ContextCompat.getDrawable(context, R.drawable.sample_drawable));正在API 19上崩溃的应用。

问题描述 投票:1回答:1

我有一个简单的布局文件,我想在主容器的背景中使用一个可绘制的文件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mlv_balance_detail_container"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    **android:background="@drawable/sample_drawable"** //this was causing crash in 4.4.2 API 19
    android:padding="@dimen/dimen_16dp">

    <TextView
        android:id="@+id/tv_policy_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:letterSpacing="0.04"
        tools:text="text"
        android:textColor="#1d252d"
        android:textSize="14sp"
        android:textStyle="normal" />

    <TextView
        android:id="@+id/tv_total_balance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_policy_text"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif"
        android:letterSpacing="0.04"
        tools:text="some text"
        android:textColor="#1d252d"
        android:textSize="12sp"
        android:textStyle="normal" />


</RelativeLayout>

然后我试着从代码中设置背景,使用

container.setBackground(ContextCompat.getDrawable(context, R.drawable.sample_drawable));

现在还在崩溃,谁能帮我解决这个问题?

android android-layout android-drawable android-relativelayout
1个回答
0
投票

我找到了一个解决这个问题的方法,虽然我还在寻找更好的答案,但目前,我是在FrameLayout里面使用ImageView,并设置Imageview的app:srcCompat属性,这是向后兼容的。

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/sample_drawable" />

        </FrameLayout>

    //rest of my layout as it is

    </RelativeLayout>

© www.soinside.com 2019 - 2024. All rights reserved.