我正在尝试使用自定义适配器为Fragment创建一个填充了消息的列表视图。我的android项目运行没有问题或错误。我可以看到消息正确地传递给构造函数。我认为我的getView不会被调用,我相信它会自动发生。我把打印件放在适配器的getView中,但它们永远不会消失。
这是我的MessageAdapter
public class MessageAdapter extends ArrayAdapter<message> {
private final Context context;
private final int layoutResourceId;
private final ArrayList<message> messages;
public MessageAdapter(Context context, int layoutResourceId, ArrayList<message> messages) {
super(context, layoutResourceId);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.messages = messages;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View row = convertView;
ViewHolder holder = null;
int direction = messages.get(i).userType;
//show message on left or right, depending on if
//it's incoming or outgoing
System.out.println("try this");
if (row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
int res = 0;
if (direction == 0) {
res = R.layout.message_right;
} else if (direction == 1) {
res = R.layout.message_left;
}
row = inflater.inflate(res, viewGroup, false);
holder = new ViewHolder();
holder.txtMessage = (TextView) row.findViewById(R.id.txtMessage);
holder.txtDate = (TextView) row.findViewById(R.id.txtDate);
row.setTag(holder);
}
System.out.println(messages.get(i).message);
holder.txtMessage.setText(messages.get(i).message);
holder.txtDate.setText(messages.get(i).time);
return row;
}
static class ViewHolder {
TextView txtMessage;
TextView txtDate;
}
}
这就是我在片段中调用适配器的地方。
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View messagesView = inflater.inflate(R.layout.messages, container, false);
ListView listView = (ListView)messagesView.findViewById(R.id.listMessages);
ArrayList<message> messages = getMessages();
MessageAdapter adapter = new MessageAdapter(getActivity(), R.id.listMessages, messages);
listView.setAdapter(adapter);
...
编辑: 按要求获取消息。
String[] messageArray = getMessages(); // get messages returns an array of json encoded rows from the db
for(int i=0; i<messageArray.length; i++) {
String theMess = null, time = null;
int userType = 0;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(messageArray[i]);
} catch (JSONException e) {
e.printStackTrace();
}
try {theMess = jsonObject.getString("message");} catch (JSONException e) {}
try {time = jsonObject.getString("time");} catch (JSONException e) {}
try {userType = jsonObject.getInt("userType");} catch (JSONException e) {}
message newMessage = new message(theMess, time, userType);
messages.add(newMessage);
}
答案 0 :(得分:0)
您缺少getSize方法。添加getsize和getItem方法后,这将按预期工作
答案 1 :(得分:0)
此外,您还必须在getview()方法中向viewgroup添加视图。
答案 2 :(得分:0)
更改
super(context, layoutResourceId);
到
super(context, layoutResourceId, messages);
您不需要getCount()
或getItem()
。除非你需要自己的特殊逻辑,否则ArrayAdapter
已经有了适用它们的实现。
答案 3 :(得分:0)
您不需要ArrayList<message> messages
,ArrayAdapter
已经维护了自己ArrayList
。您应该将消息传递给超级ctr,并使用getItem(position)
方法中的getView
。