我有两个 Buttons
嵌套在 LinearLayout
中。在这些 Buttons
之间是两个 TextViews
。在 Xml
中,我为每个 Button
都将前景设置为图像。
它在我的 Api 23
设备上运行良好。但在 Api 23
以下的其他设备上,前景图像不会显示,而是会显示默认的白色纯色。有没有办法让这些图像在 Api 23
下使用前景显示?
我们已经尝试过 FrameLayout
但它没有按照我们的意愿进行。 ImageButtons
是解决这个问题的更好方法吗?
我们应用程序的核心功能之一是,每次用户点击 Button
时,尺寸都会增加,图像也会相应地拉伸(stretch)。这是在代码中动态完成的。如果我要使用 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. 图像文件太大,造成outOfMemory
错误,进而导致按钮不显示图像。
2. foreground属性不适用于API 22及以下版本。
解决这些问题的步骤:
1. 我们减小了图像文件的大小。
2.我们将Button
替换为ImageButton
3. 在 XML
文件中,我们删除了 foreground 属性,添加了黑色背景,并通过 src
属性添加了图像。以下是一个 fragment 。
<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"/>
- 然后我们不得不更改我们的代码,通过设置
LayoutParams
动态调整按钮的高度以匹配新图像按钮的帮助:
how to change size of button dynamic in android
现在一切正常!
关于java - 如何使按钮的前景属性在 API 23 以下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979828/