本文介绍了约束布局,其中百分比未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用约束布局按如下方式制作一个宽度为70%并对齐其父视图右侧的视图

I would make a view that has 70% width and align to the right of its parent using constraint layout as follow

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.3"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="Hello text"
        app:layout_constraintLeft_toRightOf="@+id/guideline"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

TextView始终占据整个父级宽度.知道我在做什么错吗?

The TextView always occupy full parent width. Any idea what I'm doing wrong?

推荐答案

两个小而重要的变化:

  1. TextView的宽度应为0dp,即匹配约束而不与父对象匹配
  2. 指南的方向应该是垂直的,而不是水平的

代码如下:

<?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.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.3" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello text"
        app:layout_constraintLeft_toRightOf="@id/guideline"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>

输出:

还要注意,我将ConstraintLayout的高度更改为match_parent,以使准则在输出中可见.您可以将其更改回wrap_content.

Also note that I changed the ConstraintLayout height to match_parent so that the guideline was visible in the output. You can change it back to wrap_content.

这篇关于约束布局,其中百分比未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:06