如何使按钮的前景属性在API 23下工作?

时间:2016-06-22 23:24:23

标签: java android xml android-layout foreground

我在Buttons嵌套了两个LinearLayout。这些Buttons之间有两个TextViews。在Xml中,我已将前景设置为每个Buttons的图像。

它在Api 23的设备上正常运行。但是在Api 23以下的其他设备上,前景图像不会显示,而是会产生默认的白色纯色。有没有办法让这些图像使用Api 23下方的前景显示?

我们尝试了FrameLayout,但它并没有按我们的意愿去做。 ImageButtons是解决此问题的更好方法吗?

我们的应用程序的核心功能之一是,每次用户点击Button时,大小都会增加,图像会相应地延伸。这是在代码中动态完成的。如果我使用ImageButtons,我需要每次为高度和宽度设置布局参数,而不是设置高度的一行代码。

任何提示都将不胜感激!

编辑:我正在使用的代码 -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="11"
    android:background="@android:color/black">

    <Button
        android:layout_weight="5"
        android:id="@+id/firstP"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:foreground="@drawable/icebutton"
        android:scaleX="1"
        android:scaleY="1"/>

    <TextView
        android:layout_weight="0.5"
        android:id="@+id/firstPlayer"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:rotation="180"
        android:textColor="@android:color/white"
        android:background="@android:color/transparent"/>

    <TextView
        android:layout_weight="0.5"
        android:id="@+id/secondPlayer"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:background="@android:color/transparent"/>

    <Button
        android:layout_weight="5"
        android:id="@+id/secondP"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:foreground="@drawable/firebutton"
        android:scaleX="1"
        android:scaleY="1"/>

</LinearLayout>

1 个答案:

答案 0 :(得分:3)

我们发现有两个问题导致图像无法显示 1.图像文件的大小太大,造成outOfMemory错误,从而导致按钮无法显示图像。
2.前景属性不适用于API 22及以下版本。

解决这些问题的步骤:
1.我们缩小了图像文件的大小。
2.我们将Button替换为ImageButton
3.在XML文件中,我们删除了前景属性,添加了黑色背景,并通过src属性添加了图像。以下是一个片段。

<ImageButton
    android:layout_weight="5"
    android:id="@+id/firstP"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:src="@drawable/icebutton"
    android:scaleType="fitXY"
    android:background="@android:color/black"/>
  1. 我们必须通过设置LayoutParams来更改我们的代码以动态调整按钮的高度,以便在此链接的帮助下匹配新图像按钮:
    how to change size of button dynamic in android
  2. 现在一切都很完美!