-1

我是 android 技术和通过网络教程学习的新手。在绑定列表视图时,我很困惑为什么我们创建一个单独的布局文件并在 arrayadapter 中调用该布局文件

4

3 回答 3

1

为列表视图的每一行创建单独的 xml。listview 需要显示项目,因此应该使用诸如 textview、imageview 之类的视图来显示......所以根据需要,您需要该布局。

于 2013-03-13T06:06:45.817 回答
1

下面显示的代码来源:http ://www.vogella.com/articles/AndroidListView/article.html

当你创建一个简单的ListView,你会使用这样的东西:

XML:

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

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

爪哇:

ListView listView = (ListView) findViewById(R.id.mylist);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
        "Linux", "OS/2" };

// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, values);


// Assign adapter to ListView
listView.setAdapter(adapter);

创建 customListView时,您通常会执行以下操作:

package de.vogella.android.listactivity;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;

    public MySimpleArrayAdapter(Context context, String[] values) {
        super(context, R.layout.rowlayout, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        textView.setText(values[position]);
        // Change the icon for Windows and iPhone
        String s = values[position];
        if (s.startsWith("iPhone")) {
            imageView.setImageResource(R.drawable.no);
        } else {
            imageView.setImageResource(R.drawable.ok);
        }
        return rowView;
    }
}

在此示例中,如果您查看以下行: View rowView = inflater.inflate(R.layout.rowlayout, parent, false);,这R.layout.rowlayout是您的自定义布局,用于显示您的自定义ListView

有关ListView's.

于 2013-03-13T06:10:28.150 回答
1

您不必创建单独的布局。您可以在运行时创建布局。

于 2013-03-13T06:11:51.940 回答