Eug*_*sov 66
通过引入ConstraintLayout,您不必编写单行代码或使用第三方或依赖PercentFrameLayout于26.0.0中不推荐使用的代码.
以下是如何使用以下方法保持布局的1:1宽高比的示例ConstraintLayout:
<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        android:background="@android:color/black"
        app:layout_constraintDimensionRatio="H,1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </FrameLayout>
</android.support.constraint.ConstraintLayout>
或者,您可以直接在布局编辑器中编辑布局,而不是编辑XML文件:
Esp*_*dal 20
在build.gradle中添加:
compile 'com.android.support:percent:23.1.1'
并在您的layout.xml中 包装您想要遵循PercentFrameLayout内部比率的任何视图或视图组,其中:
android:layout_width="match_parent"
android:layout_height="wrap_content"
然后对于视图或视图组,你想要遵循一个比例替换 android:layout_width和android:layout_height:
    app:layout_aspectRatio="178%"
    app:layout_widthPercent="100%"
并且您有一个视图或视图组,其宽高比为16:9(1.78:1),宽度与父级匹配,相应地调整高度.
注意:删除正常的宽度和高度属性非常重要.Lint会抱怨,但它会起作用.
new*_*yca 17
您可以尝试初始设置layout_height为wrap_content.但是从那里我认为你必须进入代码.只是为了实验,在你的活动中尝试类似:
@Override
public void onResume(){
    super.onResume();
    findViewById(R.id.squareView).getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override public void onGlobalLayout() {
            View squareView = findViewById(R.id.squareView);
            LayoutParams layout = squareView.getLayoutParams();
            layout.height = squareView.getWidth();
            squareView.setLayoutParams(layout);
            squareView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });
}
R.id.squareView有id问题的观点在哪里?请注意,此代码包含在onGlobalLayout调用中以确保squareView.getWidth()具有有意义的值.
我为类似的用例创建了一个布局库。随意使用它。
将此添加到文件的顶部
repositories {
    maven {
        url  "http://dl.bintray.com/riteshakya037/maven" 
    }
}
dependencies {
    compile 'com.ritesh:ratiolayout:1.0.0'
}
在布局中的根视图上定义“app”命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
在您的布局中包含此库
<com.ritesh.ratiolayout.RatioRelativeLayout
        android:id="@+id/activity_main_ratio_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:fixed_attribute="WIDTH" // Fix one side of the layout 
        app:horizontal_ratio="2" // ratio of 2:3
        app:vertical_ratio="3">
| 归档时间: | 
 | 
| 查看次数: | 46279 次 | 
| 最近记录: |