Android的绘制对象:指定形状的宽度百分比在XML文件中?百分比、宽度、形状、对象

2023-09-06 13:48:00 作者:梦见你离开

我想创建一个我想设置为背景的一个观点一个简单的绘制对象(使用的 setBackgroundDrawable 的)。我只是想要分割的可绘制的背景成2相同的矩形(50% - 50%),用黑色填充第一想,第二个有白色:

I'm trying to create a simple Drawable that I want to set as the background for a view (using setBackgroundDrawable). I simply want to divide the background of the drawable into 2 equal rectangles (50% - 50%), the first want filled with black, the second with white:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/back_color_1">
        <shape android:shape="rectangle">
          <solid android:color="#000000" />
        </shape>
    </item>
    <item android:id="@+id/back_color_2">
        <shape android:shape="rectangle">
          <solid android:color="#FFFFFF" />
        </shape>
    </item>
</layer-list>

我怎么可以指定每个形状应该有50%的宽度,在绘制XML定义文件?类似的机器人:WIDTH =50%的

(我工作在Android 3.0,但我认为这是一个普遍的Andr​​oid的问题。)

(I'm working on Android 3.0, but I think it is a general Android question.)

P.S:可以在CSS或XAML做到这一点

P.S: You can do this in CSS or XAML.

推荐答案

您不能指定一个百分比。你需要指定一个维度的价值了。

You can't specify a percentage. You need to specify a Dimension value to it.

机器人:宽度在这里被定义:的 http://developer.android.com/reference/android/R.attr.html#width :

(重点煤矿)

必须是一个尺寸值,这是附加一个单元一个浮点数,如14.5sp。可用的单位有:PX(像素),DP(密度无关的像素),SP(以preferred字体大小缩放像素),in(英寸),mm(毫米)。

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

对于每个维度类型的定义,请参见:的http://developer.android.com/guide/topics/resources/more-resources.html#Dimension

For a definition of each dimension type, see: http://developer.android.com/guide/topics/resources/more-resources.html#Dimension

您需要创建自己的属性(见设置样式)并执行计算自己在的OnDraw(...)

You will need to create your own attribute (see styleable) and perform the calculations yourself in onDraw(...).

的例子看到这两个问题,并在其中的链接:

[机器人]定义自定义ATTRS

Declaring在Android的设置样式属性