android: 自定义 relativeLayout 中的通用图像视图(或任何其他视图)(或...)

android: generic imageview (or any other view) inside a custom relativeLayout(or...)

我知道这看起来有点傻! 如果我想错了,请纠正我。

我制作了一个自定义的 relativeLayout,它具有某种取决于屏幕尺寸的动态行为。我需要在此布局中添加一个 imageView,它继承了它的尺寸,就像它的父级一样。

我想知道是否有一种方法可以在我的自定义布局中实现 imageview class 以便每次我将它添加到布局中时,imageview 都会出现在其中?

当然,您可以在自定义 RelativeLayout 中自动添加您想要的任何 View。我看到了您可以采取的几种不同方法。

1- 为自定义 RelativeLayout 的内容创建一个 xml 布局,如果您有很多视图,也可以使用 <merge> 作为根标签:

public class CustomRelativeLayout extends RelativeLayout {

    private ImageView imageView;

    public CustomRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.custom_relative_layout, this);

        imageView = (ImageView) findViewById(R.id.image_view);
    }
}

custom_relative_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@+id/image_view"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"/>

2- 以编程方式创建 View

public class CustomRelativeLayout extends RelativeLayout {

    private ImageView imageView;

    public CustomRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        imageView = new ImageView(context);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imageView.setLayoutParams(layoutParams);
        addView(imageView);
    }
}

3- 使用您的 CustomRelativeLayout 和其中的任何 child View 创建一个 xml,然后将其包含在<include> 的其他布局。获取 onFinishInflate()

中 children View 的引用
public class CustomRelativeLayout extends RelativeLayout {

    ImageView imageView;

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        imageView = (ImageView) findViewById(R.id.image_view);
    }
}

custom_relative_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<com.example.CustomRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</com.example.CustomRelativeLayout>

并在其他地方使用

<include layout="@layout/custom_relative_layout"/>