Android:自定义RelativElayout(或..)内的通用ImageView(或任何其他视图)



我知道它似乎有点愚蠢!如果我想错了,请纠正我。

我做了一个自定义的Relativelayout,其具有某种动态行为,取决于屏幕尺寸。我需要在此布局中添加一个图像视图,该布局像父母一样继承其尺寸。

我想知道我是否有一种方法可以在自定义布局类中实现imageView,以便每次在布局中添加时,imageView都会出现?

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

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

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和任何子View创建一个XML,而不是将其包含在具有<include>的其他布局中。在onFinishInflate()

中获取儿童View s的参考
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"/>

相关内容

最新更新