如何在ListView上放置背景?

时间:2015-05-20 20:11:41

标签: android android-listview android-xml

我将使用ListView开展活动。我想为ListView添加一个背景,但是当我降低图像时,它会保持在同一侧但ListView移动。我希望图片适应ListView

我的代码:

<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>

我尝试使用ScrollView,但ListView仅显示第一项。

1 个答案:

答案 0 :(得分:0)

创建一个扩展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);
    }
}