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

标签 android xml android-linearlayout

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

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/

相关文章:

android - 线性布局不等宽

android - 获取电池电压

java - 解码意外元素错误

android - ImageView 和 LinearLayout, ImageView 在图像的顶部和底部出现空白

android - 如何在 Imageview 的顶部或底部添加 ad-mob(广告横幅)?

c# - XMLDocument.Load(url) 通过代理

android - 如何使 ListView 可点击并从 mysql 数据库中删除数据?

android - 什么是 Root View ?

java - Android Studio setText 并在代码中设置字符串

java - 如何在 Java 中从 String 创建 XML 对象?