如何向ListView添加不同类型的视图

时间:2017-04-08 13:08:44

标签: java android listview android-studio android-arrayadapter

我想将文字和图片添加到TextView ArrayApapter。 如果这是ArrayAdapter

的定义
new ArrayAdapter<View>(getContext(),R.id.element_manual_list, viewsOfPage);

我可以使用element_manual_list TextViewImageView,但我想要两者。我该如何实现呢?或者是否有更简单的方法将带有图像的userManual文字写入Scrollable View? 可能是HTML样式的东西吗?

1 个答案:

答案 0 :(得分:0)

您需要创建自己的适配器类:

    public class MyAdapter extends ArrayAdapter<User> {
    public MyAdapter(Context context, ArrayList<User> users) {
        super(context, 0, users);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        User user = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
        }
        // Lookup view for data population
        TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
        ImageView ivPhoto = (ImageView) convertView.findViewById(R.id.ivPhoto);
        // Populate the data into the template view using the data object
        tvName.setText(user.name);
        ivPhoto.setImageResource(user.photo);
        // Return the completed view to render on screen
        return convertView;
    }
}

然后是行的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/ivPhoto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/sym_def_app_icon" />

<TextView
    android:id="@+id/tvName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Name" />

然后你的自定义例如User class:

    public class User {
    public String name;
    public int photo;

    public User(String name, int photo) {
        this.name = name;
        this.photo = photo;
    }
}

在你的主要文章中写下:

 // Construct the data source
    ArrayList<User> arrayOfUsers = new ArrayList<User>();
    // Create the adapter to convert the array to views
    MyAdapter adapter = new MyAdapter(this, arrayOfUsers);
    // Attach the adapter to a ListView
    ListView listView = (ListView) findViewById(R.id.lvItems);
    listView.setAdapter(adapter);

    // Add item to adapter
    User newUser = new User("Nathan", R.drawable.logo);
    adapter.add(newUser);