【问题标题】:How to put a background on ListView?如何在 ListView 上放置背景?
【发布时间】:2015-05-20 20:11:41
【问题描述】:

我要与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 只显示第一项。

【问题讨论】:

  • 一种方法是分割背景并在列表项的视图中显示部分。
  • 在您的 XML 文件中将 android:background="@drawable/fondomax" 添加到 ListView
  • 这种方式无效

标签: android android-listview android-xml


【解决方案1】:

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

【讨论】:

  • 但是我用的是extends Activity...是一样的吗??
  • 创建一个新的 java 文件并将其命名为 ScrollableBackgroundListView.java(这是一个不同于 MainActivity 文件(或任何 Activity)的文件)。
  • 在您的 XML 中,将 ListView 替换为 com.myapplication.ScrollableBackgroundListViewcom.myapplication 应替换为您的包名)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多