【问题标题】:List View shows objects instead of rows in android列表视图显示对象而不是android中的行
【发布时间】:2012-03-03 11:04:42
【问题描述】:

我有一个要求,我必须生成一个列表视图,其中每一行都有一个图标和一个名称。代码看起来像这样。

public class MyListActivity extends ListActivity {
...
...

    ArrayList<StringBuilder> categories = new ArrayList<StringBuilder>();
    categories.add(new StringBuilder("xyaq"));
    categories.add(new StringBuilder("wers"));
    categories.add(new StringBuilder("test2"));
    categories.add(new StringBuilder("asfda"));
    categories.add(new StringBuilder("hoyio"));

    ArrayList<RelativeLayout> departments = new ArrayList<RelativeLayout>();

    for (StringBuilder category : categories) {
        RelativeLayout categoryRow = (RelativeLayout) mInflater.inflate(
                R.layout.products_row, null);

        ImageView tempImage = (ImageView) categoryRow.getChildAt(0);
        tempImage.setBackgroundResource(R.drawable.ic_launcher);
        TextView tempTextView = (TextView) categoryRow.getChildAt(1);
        tempTextView.setText(category);
        departments.add(categoryRow);
    }
    ArrayAdapter<RelativeLayout> departmentAdaptor = new ArrayAdapter<RelativeLayout>(
            this, android.R.layout.simple_list_item_1, departments);

    setListAdapter(departmentAdaptor);
}

products_row.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
    android:id="@+id/deptIcon"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="#FFFFFF"
    android:clickable="false"
    android:contentDescription="@string/hello"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/deptName"
    android:layout_width="fill_parent"
    android:layout_height="54dp"
    android:layout_alignLeft="@id/deptIcon"
    android:layout_marginLeft="80dp"
    android:gravity="left|center"
    android:textSize="25dp"
    android:textStyle="bold" />

</RelativeLayout>

我面临的问题是我看不到带有图像和相应文本的行。相反,它显示了相关布局对象的列表。

【问题讨论】:

    标签: android


    【解决方案1】:

    这不是实现您想要实现的目标的正确方法。 您需要为此创建自定义适配器。

    查看此链接并检查我的答案: Listview with Image,Text and Checkbox

    有完整的 Activity 代码并包含一个扩展 ArrayAdapte 的内部类 MyAdapter。

    【讨论】:

    • 非常感谢@Pankaj。创建一个自定义适配器就可以了!但是我很想知道为什么我的实现方式(将列表行的arraylist传递给arrayadapter)不起作用? :-)
    • 它不会自动将ArrayList中的Relative分配给我们的listview。我们必须手动将数据分配给组件。这就是listview的工作方式
    • 哦..好的。知道了。非常感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2016-11-26
    • 1970-01-01
    • 2020-04-05
    • 2021-09-20
    • 2020-07-27
    相关资源
    最近更新 更多