我正在尝试开发一个 Android 布局,其中我有一个 Image
和 some text
。
我希望图像1 屏高,其余内容将在向下滚动时显示。
我应该在 layout.xml 中设置什么值。所以图像正好(与设备无关)1 屏高?
为了使问题更清楚,使用 css 我可以使用 following code 轻松获得全高屏幕图像:
<html>
<style>
html, body {
height: 100%;
}
.image {
height: 100%;
background-image: url(http://kolobee.com/images/stings/baelo-claudia.1ovl/ad2p/620x620.jpg);
background-position: center;
}
</style>
<body>
<div class="image"></div>
<h1>Title</h1>
<p>More text</p>
</body>
</html>
最佳答案
您可以使用覆盖 ImageView 类的 onMeasure() 方法的自定义 View 来实现此目的。下面是自定义 View ,以及与您问题中的图像相匹配的布局。
(请注意,此方法未考虑 ActionBar 占用的空间量。如果您使用的是自定义 View ,则需要进一步调整。)
package com.example.testview;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.ImageView;
public class FullScreenImageView extends ImageView {
private DisplayMetrics mMetrics;
public FullScreenImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mMetrics = new DisplayMetrics();
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
WindowManager windowManager = (WindowManager) ((Activity)getContext()).getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(mMetrics);
setMeasuredDimension(mMetrics.widthPixels, mMetrics.heightPixels);
}
}
布局 xml 类似于:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<com.example.testview.FullScreenImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Title" />
<Text
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Text" />
</LinearLayout>
</ScrollView>
关于android - 如何将布局元素高度定义为屏幕高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17619754/