gpt4 book ai didi

android - 自定义方形线性布局。如何?

转载 作者:IT老高 更新时间:2023-10-28 23:05:07 24 4
gpt4 key购买 nike

我为方形布局创建了自己的类:

public class SquareLayout extends LinearLayout{

public SquareLayout(Context context) {
super(context);
}

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

public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}


@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);
}

然后,在我的 xml 中:

...
<com.myApp.SquareLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="horizontal" >

<ImageView
android:id="@+id/cellImageView"
android:adjustViewBounds="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:padding="2dp"
android:scaleType="centerCrop"
android:src="@drawable/image" />
</com.myApp.SquareLayout>
...

在我的 java 代码中没有写更多的东西。但相反,如果我的布局和图像,我只看到一个白色矩形......

我错了什么?

最佳答案

//你忘记调用 super.onMeasure(widthMeasureSpec, widthMeasureSpec);

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);

}

//xml文件

<com.example.testapplication.SquareLayout
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="horizontal" >

<ImageView
android:id="@+id/cellImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:adjustViewBounds="true"
android:padding="2dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher" />

</com.example.testapplication.SquareLayout>

关于android - 自定义方形线性布局。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16748124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com