XML中百分比的Margin/Padding

8

我是Android开发的新手。我想在Xml中设置边距和内边距,但不要用dp或px,而是用百分比。有没有办法做到这一点?


嘿,我认为这是不可能的。 请看这里 - LuminiousAndroid
4个回答

5

虽然不可能,但是您可以在Java代码中通过以下方式获取屏幕的宽度和高度:

 Display display = getWindowManager().getDefaultDisplay(); 
 int width = display.getWidth();
 int height = display.getHeight();

然后从屏幕尺寸计算您的边距,并通过以下方式设置:

margin: 值px;

  setmargin(int x) //method of view/layout.

通过这种方式,您可以根据屏幕大小而不是固定设置边距,基本上就像从Java代码中设置百分比一样。


1
使用getWidth()和getHeight()在API级别13+已被弃用。http://developer.android.com/reference/android/view/Display.html。请改用getSize(point)。 - maraci
1
@maraci,请查看我针对您的问题所提供的另一个答案链接 >> https://dev59.com/6Ggu5IYBdhLWcg3wOUm-#11483404 - AAnkit

1
使用 ConstraintLayout 中引入的 指南,这变得可行了。
以下是 TextView 放置在屏幕宽度的 60% 和屏幕高度的 25% 的示例:

Layout Editor

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintLeft_toLeftOf="@+id/guideline1"
        app:layout_constraintTop_toTopOf="@+id/guideline2" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline1"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.6" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

</android.support.constraint.ConstraintLayout>

0

如果您正在尝试在Android中以百分比共享控件的屏幕宽度。最好的方法是使用weight属性对它们进行设置。查看以下网址获取更多详细信息。

Android布局参数指南

敬礼, Aqif Hamid


0

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