[英]How to put a background on ListView?
I'am to develop an activity with ListView
. 我正在使用ListView
开发一项活动。 I want to put a background to the ListView
but when I lower the image remains on the same side but ListView
moves. 我想为ListView
设置背景,但是当我降低图像时,图像保持在同一侧,但是ListView
移动。 I want the image is adapted to ListView
. 我想将图像调整为ListView
。
My code: 我的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/fondomax" >
<ListView
android:id="@+id/lista"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
></ListView>
I have tried with ScrollView
but the ListView
only shows the first item. 我已经尝试过使用ScrollView
但是ListView
仅显示第一项。
Create a custom class extending ListView, and override dispatchDraw(...)
: 创建一个扩展ListView的自定义类,并重写dispatchDraw(...)
:
public class ScrollableBackgroundListView extends ListView {
private Bitmap background;
public ScrollableBackgroundListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas) {
int topPosition;
if (getChildCount() > 0) {
topPosition = getChildAt(0).getTop();
} else {
topPosition = 0;
}
int listViewWidth = getWidth();
int listViewHeight = getHeight();
int backgroundWidth = background.getWidth();
int backgroundHeight = background.getHeight();
for (int y = topPosition; y < listViewHeight; y += backgroundHeight) {
for (int x = 0; x < listViewWidth; x += backgroundWidth) {
canvas.drawBitmap(background, x, y, null);
}
}
super.dispatchDraw(canvas);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.