我在Android应用中有一个POJO列表,我目前正在listview / listitem中显示其中一个字段,如下所示:
List<NotificationItem> notifItems;
// snip, populate
ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.notification_item, notifItems);
ListView listView = (ListView) findViewById(R.id.notification_listview);
listView.setAdapter(adapter);
我的理解是listivew或者适配器使用POJO的toString,这是
public String toString() {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
return _notificationTitle + " | " + dateFormatter.format(_notificationReceivedDate);
}
R.id.notificationitem是
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16sp"
android:textStyle="bold"></TextView>
到目前为止一切顺利,但我想要做的是在notificationitem布局文件中添加元素,然后更新Java代码以填充新字段。
这是怎么做到的?我不太了解适配器如何知道/将toString值放入notificationitem中的一个字段中。
答案 0 :(得分:1)
public class NotificationItem {
//your fields here
}
//-----------------------
public class NotifAdapter extends BaseAdapter {
Context context;
List<NotificationItem> data;
public NotifAdapter(Context context, List<NotificationItem> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.your_row_layout,parent, null);
TextView tx = convertView.findViewById(R.id.your_widget_inside_row_layout);
tx.setText(data.yourDataPropery);
return convertView;
}
}
// In your activity
NotifAdapter adapter = new NotifAdapter(this, ArrayList<NotificationItem>);
listView.setAdapter(adapter);