2017-04-05 151 views
0

我有一個Android應用程序一個POJO的列表,我目前顯示領域之一列表視圖/列表項,像這樣:顯示多個字段列表視圖

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,這是

public String toString() { 
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm"); 
    return _notificationTitle + " | " + dateFormatter.format(_notificationReceivedDate); 
} 

R.id.notificationitem的的toString是

<?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的一個字段中。

+2

您需要創建一個自定義適配器。 –

+0

您需要一些自定義適配器,如:'class Adapter extends' [MatchableArrayAdapter](https://gist.github.com/pskink/2dd4d17a93caf02ff696533e82f952b0)' {...'並覆蓋它的'onBind()'方法,額外獎勵:如果您想要簡單的項目過濾,請覆蓋'matches()'方法 – pskink

回答

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);