programing

상대 레이아웃의 백분율 너비

linuxpc 2023. 7. 15. 09:46
반응형

상대 레이아웃의 백분율 너비

있습니다.Activity내 안드로이드 앱에서.아래 이미지는 다음과 같습니다.

enter image description here

저는 다음 XML로 이 레이아웃을 만들 수 있었습니다.문제는, 그것이 약간 진부하다는 것입니다.호스트 EditText의 너비를 하드 코딩해야 했습니다.구체적으로, 저는 다음을 명시해야 했습니다.

android:layout_width="172dp" 

호스트 및 포트에 백분율 너비를 지정합니다. 편집텍스트는. (호스트의 경우 80%, 포트의 경우 20% 정도)이것이 가능합니까?다음 XML은 내 Droid에서 작동하지만 모든 화면에서 작동하지는 않는 것 같습니다.저는 정말로 더 강력한 솔루션을 원합니다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/host_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/home"
        android:paddingLeft="15dp"
        android:paddingTop="0dp"
        android:text="host"
        android:textColor="#a5d4e2"
        android:textSize="25sp"
        android:textStyle="normal" />

    <TextView
        android:id="@+id/port_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/home"
        android:layout_toRightOf="@+id/host_input"
        android:paddingTop="0dp"
        android:text="port"
        android:textColor="#a5d4e2"
        android:textSize="25sp"
        android:textStyle="normal" />

    <EditText
        android:id="@+id/host_input"
        android:layout_width="172dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/host_label"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:background="@android:drawable/editbox_background"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/port_input"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/host_label"
        android:layout_marginTop="4dp"
        android:layout_toRightOf="@id/host_input"
        android:background="@android:drawable/editbox_background"
        android:inputType="number" />

    <TextView
        android:id="@+id/username_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/host_input"
        android:paddingLeft="15dp"
        android:paddingTop="15dp"
        android:text="username"
        android:textColor="#a5d4e2"
        android:textSize="25sp"
        android:textStyle="normal" />

    <EditText
        android:id="@+id/username_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/username_label"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:background="@android:drawable/editbox_background"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/password_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username_input"
        android:paddingLeft="15dp"
        android:paddingTop="15dp"
        android:text="password"
        android:textColor="#a5d4e2"
        android:textSize="25sp"
        android:textStyle="normal" />

    <EditText
        android:id="@+id/password_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/password_label"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="4dp"
        android:background="@android:drawable/editbox_background"
        android:inputType="textPassword" />

    <ImageView
        android:id="@+id/home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="false"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="15dp"
        android:scaleType="fitStart"
        android:src="@drawable/home" />

    <Button
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password_input"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:text="   login   "
        android:textSize="18sp" >
    </Button>

</RelativeLayout>

은 당은찾있다니습고신▁the다▁for를 찾고 .android:layout_weight할 수 .백분율을 사용하여 레이아웃을 정의할 수 있습니다.

다음 예제에서는 왼쪽 단추가 공간의 70%를 사용하고 오른쪽 단추가 30%를 사용합니다.

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

    <Button
        android:text="left" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight=".70" /> 

    <Button
        android:text="right" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight=".30" />

</LinearLayout>

모든 종류의 보기에서 동일하게 작동하며 필요에 따라 일부 편집 텍스트로 단추를 바꿀 수 있습니다.

설정해야 합니다.layout_width0dp보기의 크기가 제대로 조정되지 않을 수 있습니다.

참고로 무게 합계가 1일 필요는 없습니다. 이렇게 읽는 것이 더 쉽다는 것을 알게 되었습니다.첫 번째 가중치를 7로 설정하고 두 번째 가중치를 3으로 설정하면 동일한 결과를 얻을 수 있습니다.

이는 70/30 스플릿에 대한 원래 질문에 대한 답은 아니지만, 구성 요소 간의 50/50 스플릿의 특수한 경우에는 보이지 않는 스트럿을 중앙에 배치하여 관심 있는 두 구성 요소를 배치하는 방법이 있습니다.

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <View android:id="@+id/strut"
        android:layout_width="0dp"
        android:layout_height="0dp" 
        android:layout_centerHorizontal="true"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/strut"
        android:layout_alignParentLeft="true"
        android:text="Left"/> 
    <Button 
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/strut"
        android:layout_alignParentRight="true"
        android:text="Right"/>
</RelativeLayout>

이것은 꽤 흔한 경우이기 때문에, 이 해결책은 호기심 이상입니다.그것은 약간의 해킹이지만, 빈 제로 사이즈 스트럿은 매우 적은 비용이 들 것이기 때문에 효율적입니다.

하지만 일반적으로 재고 안드로이드 레이아웃에는 너무 많은 것을 기대하지 않는 것이 좋습니다.

업데이트 1

@EmJiHashPercentRelativeLayout은 API 레벨 26.0.0에서 더 이상 사용되지 않습니다.

아래는 구글 코멘트를 인용한 것입니다.

이 클래스는 API 수준 26.0.0에서 더 이상 사용되지 않습니다. 대신 제약 조건 레이아웃 및 관련 레이아웃을 사용하십시오.다음은 구속조건 레이아웃을 사용하여 백분율 레이아웃의 기능을 복제하는 방법을 보여줍니다.


구글은 새로운 API를 소개했습니다. 안드로이드의지지율

그런 다음 보기별로 취할 백분율을 지정하면 됩니다.

다음과 같은 컴파일 종속성 추가

implementation 'com.android.support:percent:22.2.0

이 경우, PercentRelativeLayout은 백분율로 배치할 수 있는 것입니다.

 <android.support.percent.PercentRelativeLayout
     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">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentRelativeLayout>

상대 레이아웃 내에서 비율을 사용하여 뷰의 치수를 정의할 수 없습니다.가장 좋은 방법은 선형 레이아웃과 가중치 또는 사용자 정의 레이아웃을 사용하는 것입니다.

새로운 퍼센트 지원 라이브러리를 볼 수 있습니다.

compile 'com.android.support:percent:22.2.0'

문서

견본의

PercentRelativeLayout을 사용할 수 있습니다. 는 최근에 문서화되지 않은 설계 지원 라이브러리에 추가된 것으로, 서로 관련된 요소뿐만 아니라 사용 가능한 공간의 총 백분율도 지정할 수 있습니다.

백분율 기반 치수 및 여백을 지원하는 상대 레이아웃의 하위 클래스입니다."백분율" 접미사가 있는 속성을 사용하여 치수 또는 자식 여백을 지정할 수 있습니다.

<android.support.percent.PercentRelativeLayout
     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">
  <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_widthPercent="50%"
      app:layout_heightPercent="50%"
      app:layout_marginTopPercent="25%"
      app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout>

백분율 패키지는 앱에서 백분율 기반 차원을 추가하고 관리할 수 있는 API를 제공합니다.

사용하려면 이 라이브러리를 Gradle 종속성 목록에 추가해야 합니다.

dependencies {
    compile 'com.android.support:percent:22.2.0'//23.1.1
}

PercentRelativeLayout은 26.0.0에서 더 이상 사용되지 않으며 RelativeLayout 내부의 LinearLayout과 같은 중첩된 레이아웃은 성능에 부정적인 영향을 미치므로(ConstraintLayout의 성능 이점 이해) 백분율 너비를 달성하는 가장 좋은 옵션은 RelativeLayout을 ConstraintLayout으로 바꾸는 것입니다.

이것은 두 가지 방법으로 해결할 수 있습니다.

솔루션 #1 백분율 오프셋이 있는 지침 사용

Layout Editor

<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/host_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Host"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="@+id/host_input" />

    <TextView
        android:id="@+id/port_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Port"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="@+id/port_input" />

    <EditText
        android:id="@+id/host_input"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:inputType="textEmailAddress"
        app:layout_constraintTop_toBottomOf="@+id/host_label"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/guideline" />

    <EditText
        android:id="@+id/port_input"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:inputType="number"
        app:layout_constraintTop_toBottomOf="@+id/port_label"
        app:layout_constraintLeft_toLeftOf="@+id/guideline"
        app:layout_constraintRight_toRightOf="parent" />

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

</android.support.constraint.ConstraintLayout>

솔루션 #2 텍스트 편집을 위해 가중된 너비의 체인 사용

Layout Editor

<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/host_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Host"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="@+id/host_input" />

    <TextView
        android:id="@+id/port_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Port"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="@+id/port_input" />

    <EditText
        android:id="@+id/host_input"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:inputType="textEmailAddress"
        app:layout_constraintHorizontal_weight="0.8"
        app:layout_constraintTop_toBottomOf="@+id/host_label"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/port_input" />

    <EditText
        android:id="@+id/port_input"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:inputType="number"
        app:layout_constraintHorizontal_weight="0.2"
        app:layout_constraintTop_toBottomOf="@+id/port_label"
        app:layout_constraintLeft_toRightOf="@+id/host_input"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>

두 경우 모두, 당신은 다음과 같은 것을 얻습니다.

Result View

사용자 정의 보기를 생성하여 이 문제를 해결했습니다.

public class FractionalSizeView extends View {
  public FractionalSizeView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public FractionalSizeView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width * 70 / 100, 0);
  }
}

상대 레이아웃 내에서 다른 뷰를 정렬하는 데 사용할 수 있는 보이지 않는 스트럿입니다.

갱신하다

@EmJiHashPercentRelativeLayout 및 PercentFrameLayout은 API 수준 26.0.0에서 더 이상 사용되지 않습니다.

구속조건 레이아웃 사용 고려

구글은 안드로이드라고 불리는 새로운 API를 소개했습니다.지지율

백분율 상대 레이아웃

프레임 레이아웃 비율

다음과 같은 컴파일 종속성 추가

compile 'com.android.support:percent:23.1.1'

차원을 백분율로 지정할 수 있으므로 두 가지 이점을 모두 얻을 수 있습니다.RelativeLayout percentage

 <android.support.percent.PercentRelativeLayout
         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
         app:layout_widthPercent="40%"
         app:layout_heightPercent="40%"
         app:layout_marginTopPercent="15%"
         app:layout_marginLeftPercent="15%"/>
 </android.support.percent.PercentRelativeLayout/>

PercentRelativeLayout은 지원 라이브러리의 Revision 26.0.0에서 더 이상 사용되지 않습니다.

구글은 제약 레이아웃이라고 불리는 새로운 레이아웃을 도입했습니다.

라이브러리를 모듈 수준의 build.gradle 파일에 종속성으로 추가합니다.

     dependencies {
        compile 'com.android.support.constraint:constraint-layout:1.0.1'
      }

레이아웃 파일에 추가하기만 하면 됩니다.

<?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">
</android.support.constraint.ConstraintLayout>

제약

제약 조건은 위젯을 정렬 상태로 유지하는 데 도움이 됩니다.아래에 표시된 구속조건 핸들과 같은 앵커를 사용하여 다양한 위젯 간의 정렬 규칙을 결정할 수 있습니다.

  1. Wrap Content보기는 내용에 맞게 필요에 따라 확장됩니다.
  2. Match Constraints보기는 여백을 고려한 후 제약 조건의 정의를 충족하기 위해 필요에 따라 확장됩니다.그러나 지정된 차원에 하나의 제약 조건만 있는 경우에는 내용에 맞게 보기가 확장됩니다.높이 또는 너비에서 이 모드를 사용하면 크기 비율을 설정할 수도 있습니다.
  3. Fixed아래 텍스트 상자에 특정 치수를 지정하거나 편집기에서 보기 크기를 조정합니다.
  4. Spread보기는 균등하게 분포되어 있습니다(마진이 계산된 후).기본값입니다.
  5. Spread inside첫 번째 보기와 마지막 보기는 체인의 양쪽 끝에 있는 제약 조건에 부착되고 나머지는 고르게 분포됩니다.
  6. Weighted체인이 내부에서 확산 또는 확산되도록 설정된 경우 하나 이상의 뷰를 "일치 제약 조건"(0dp)으로 설정하여 나머지 공간을 채울 수 있습니다.은 " 제약 조건"으로 뷰 " "layout_constraint"를 각할 수 .Horizontal_weight 및 layout_constraintVertical_weight 속 성선형 레이아웃의 layout_weight에 익숙한 경우에도 동일한 방식으로 작동합니다.따라서 가중치가 가장 높은 보기는 가장 많은 공간을 얻고, 가중치가 같은 보기는 동일한 공간을 얻습니다.
  7. Packed뷰는 (마진이 계산된 후) 함께 채워집니다.그런 다음 체인의 헤드 뷰 바이어스를 변경하여 전체 체인의 바이어스(왼쪽/오른쪽 또는 위/아래)를 조정할 수 있습니다.
  8. Center Horizontally or Center Vertically빠르게 를 모두 중 오른쪽 단추로 Vertical을 또는 .
  9. Baseline alignment뷰의 텍스트 기준선을 다른 뷰의 텍스트 기준선에 맞춥니다.
  10. Constrain to a guideline보기를 제한할 수 있는 수직 또는 수평 가이드라인을 추가할 수 있으며, 앱 사용자는 이 가이드라인을 볼 수 없습니다.레이아웃 가장자리를 기준으로 dp 단위 또는 백분율을 기준으로 레이아웃 내에 가이드라인을 배치할 수 있습니다.
  11. Adjust the constraint bias뷰의 양쪽에 구속조건을 추가하면(동일한 차원의 뷰 크기가 "고정" 또는 "랩 내용"임) 뷰는 기본적으로 50%의 치우침으로 두 구속조건 사이의 중앙에 배치됩니다.할 수 .
  12. Set size as a ratio뷰 치수 중 하나 이상이 "일치 제약 조건"(0dp)으로 설정된 경우 뷰 크기를 16:9와 같은 비율로 설정할 수 있습니다.

당신은 공식 문서에서 더 많은 것을 배울 수 있습니다.

흥미롭게도 @olefevre의 답변을 바탕으로 "보이지 않는 스트럿"으로 50/50 레이아웃을 수행할 수 있을 뿐만 아니라 2의 거듭제곱을 포함하는 모든 종류의 레이아웃을 수행할 수 있습니다.

예를 들어, 너비를 4개의 동일한 부분(실제로는 3개, 가중치는 1, 1, 2)으로 나누는 레이아웃이 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <View
        android:id="@+id/strut"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:background="#000000" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/strut" >

        <View
            android:id="@+id/left_strut"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_toLeftOf="@+id/strut"
            android:layout_centerHorizontal="true"
            android:background="#000000" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignRight="@+id/left_strut"
            android:text="Far Left" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_toRightOf="@+id/left_strut"
            android:text="Near Left" />
    </RelativeLayout>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/strut"
            android:layout_alignParentRight="true"
            android:text="Right" />

</RelativeLayout>

레이아웃 가중치를 통해 이 작업을 수행할 수 있습니다.가중치는 화면에서 클레임되지 않은 부분이 분할되는 방식을 나타냅니다.각 EditText에 layout_width를 0으로 지정하고 비례 가중치를 부여합니다.즉, 첫 번째 사용자가 두 배의 공간을 차지하려면 하나에 2의 가중치를 부여하고 다른 하나에 1의 가중치를 부여합니다.

두 개의 텍스트 뷰 호스트와 포트를 독립적인 선형 레이아웃으로 수평으로 배치하고 Android:layout_weight를 사용하여 백분율을 만듭니다.

레이아웃 xml에서 percent 또는 java 식을 직접 사용할 수 있는 https://github.com/mmin18/FlexLayout 을 확인합니다.

<EditText
    app:layout_left="0%"
    app:layout_right="60%"
    app:layout_height="wrap_content"/>
<EditText
    app:layout_left="prev.right+10dp"
    app:layout_right="100%"
    app:layout_height="wrap_content"/>

언급URL : https://stackoverflow.com/questions/4961355/percentage-width-in-a-relativelayout

반응형