Android Drawable:在XML文件中以百分比指定形状宽度?

28

我试图创建一个简单的Drawable,我想将它设置为视图的背景(使用 setBackgroundDrawable )。 我只想将可绘制对象的背景分成2个相等的矩形(50% - 50%),第一个填充黑色,第二个填充白色:

<?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>

如何在drawable XML定义文件中指定每个形状的宽度为50%?类似于android:width="50%"

(我正在使用Android 3.0,但我认为这是一个普遍的Android问题。)

P.S:您可以在CSS或XAML中完成此操作。

5个回答

13
您无法指定百分比,需要将其指定为尺寸值。 在此处定义了android:width:http://developer.android.com/reference/android/R.attr.html#width
(重点是我的)
必须是尺寸值,它是一个浮点数,附加有如“14.5sp”等单位。可用的单位有:px(像素),dp(与密度无关的像素),sp(根据首选字体大小缩放像素),in(英寸),mm(毫米)。
有关每种尺寸类型的定义,请参见:http://developer.android.com/guide/topics/resources/more-resources.html#Dimension 您需要创建自己的属性(请参阅styleable),并在onDraw(...)中执行计算。
请参见以下两个问题及其中的链接以获取示例: - 定义自定义属性 - 声明Android可样式化属性

5

没有真正的百分比设置,但您可以接近。

似乎最简单的方法是将图像用作背景可绘制物,并只需进行黑白分割图像。

我知道的另一种分割任何内容的方法是使用2个视图,每个视图都有自己的背景色,并且每个视图的android:layout_weight属性都赋予相同的正值(即50/50)。 它们将会分割可用空间。

希望这能帮到您!


2

我发现实现这个功能的方法是创建一个继承自RelativeLayout的类,重写onMeasure方法。在这个阶段,视图的高度已知,所以我获取了背景,并使用setLayerInset手动设置了项目的插入。

    LayerDrawable bg = (LayerDrawable)getBackground();
    int h = getMeasuredHeight();
    bg.setLayerInset(1, 0, 0, 0, h/2);

虽然这种方法有点繁琐,但在大多数情况下,chris提供的答案应该已经足够了。


2
android:layout_weight=".20" 是以百分比方式实现布局最好的方法。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
    android:id="@+id/logTextBox"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight=".20"
    android:maxLines="500"
    android:scrollbars="vertical"
    android:singleLine="false"
    android:text="@string/logText" >
</TextView>

</LinearLayout>

0

正如Swapnil所说的,最好的方法是在LinearLayout中使用layout_weight。 如果你要水平布局,将layout_width设置为"fill_parent",然后将layout_weight设置为你想要的百分比。从下面的示例开始,并通过调整layout_width值来熟悉它(或添加更多的视图以更好地理解)。

<LinearLayout    
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation = "horizontal" >

    <View
      android:layout_width="fill_parent"
      android:layout_height="30dip"
      android:layout_weight="0.5"
      android:background="#aaffaa" />
    <View
      android:layout_width="fill_parent"
      android:layout_height="30dip"
      android:layout_weight="0.5"
      android:background="#aaaaff" />
</LinearLayout>

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