我知道它似乎有点愚蠢!如果我想错了,请纠正我。
我做了一个自定义的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"/>