线性布局以正方形形式展示

7

是否可以动态地在LinearLayout中嵌套一个等高等宽的LinearLayout?我不想指定具体数值,只要高度与可能的宽度相同即可。

谢谢

3个回答

16

我有同样的问题,而且我无法找到只使用XML解决它的方法。因此,我编写了自定义布局,并从XML中引用它。

public class SquareLayout extends LinearLayout {

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
            // or you can use this if you want the square to use height as it basis
            // super.onMeasure(heightMeasureSpec, heightMeasureSpec); 
    }
}

然后在xml中像这样引用它

<your.package.SqureLayout .....
</your.package.SquareLayout>

如果有最简单的解决方案,我会很高兴知道它。


这种最简单的解决方案是否存在任何情况下无法奏效,需要更复杂的解决方案,例如Alex North的答案或[SquareFrameLayout](http://androidxref.com/5.1.1_r6/xref/development/samples/browseable/ActivitySceneTransitionBasic/src/com.example.android.activityscenetransitionbasic/SquareFrameLayout.java)的Android实现? - TechAurelian
@Mojo Risin,现在有一个更简单的解决方案。请查看SquareLayout:https://dev59.com/nVbUa4cB1Zd3GeqPAJzZ#46143213。 - Kaushik NP
它还根据两个维度(高度/宽度)中哪一个更小来提供自动调整。 - Kaushik NP

2

对 Mojo 的回答进行扩展,以便根据上下文处理约束维度的高度或宽度:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = Math.min(width, height);
    // Call super with adjusted spec
    super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
}

什么情况下需要这样做,而Mojo Risin的解决方案不足以解决问题? - TechAurelian

0

看看SquareLayout,这是一个Android库,它提供了一个包装类来呈现不同布局的正方形尺寸,而不会失去任何核心功能。

尺寸是在布局渲染之前计算的,因此一旦获取视图,就没有重新渲染或任何调整。

要使用该库,请将以下内容添加到您的build.gradle中:

repositories {
    maven {
        url "https://maven.google.com"
    }
}

dependencies {
    compile 'com.github.kaushikthedeveloper:squarelayout:0.0.3'
}

你的 XML 将会长成这样:

<!-- Inner Linear Layout -->   
<com.kaushikthedeveloper.squarelayout.SquareLinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

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