起初我试图重新调整我的LinearLayout并以编程方式查看此问题。
Adjusting linear layout programatically
如何引发另一个异常,特别是IllegalStateException(说“指定的子节点已经有父节点”)
我的适配器中发生的错误特别是在这部分中(第二个if语句):
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_item, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
textChat = (TextView) row.findViewById(R.id.textMessage);
thumbPhoto = (ImageView) row.findViewById(R.id.thumbPhoto);
ChatString chat = getItem(position);
if(chat.mLeft){
textChat.setText(chat.mText);
}else{
wrapper.removeViewAt(1);
wrapper.addView(thumbPhoto, 0);
textChat.setText(chat.mText);
}
return row;
}
这就是适配器在其根视图中的使用方式(我怀疑这将是罪魁祸首,但我不确定如何处理它):
这段代码驻留在AsyncTask的onPostExecute()
中Result is an ArrayList<Chat>
for(Chat chat : result){
if(chat.senderId != mAccount.accId){
adapter.add(new ChatString(false, chat.chatMessage));
}else{
adapter.add(new ChatString(true, chat.chatMessage));
}
}
该适配器的功能简要说明:
适配器假设在其根视图中向列表视图添加新的“聊天气泡”。
任何人都可以帮我吗?
修改1 我尝试了以下解决方案(仍然没有运气):
// Removing the parent.
if(chat.mLeft){
textChat.setText(chat.mText);
}else{
View view = (View) wrapper.getParent();
wrapper.removeView(view);
wrapper.removeViewAt(1);
wrapper.addView(thumbPhoto, 0);
textChat.setText(chat.mText);
}
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_item, null); <---- CHANGING THIS BIT
}
答案 0 :(得分:1)
您可以这样编辑getView:
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChatString chat = getItem(position);
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Here, inflate 2 different layouts
if(chat.mLeft){
row = inflater.inflate(R.layout.chat_item, parent, false);
} else {
row = inflater.inflate(R.layout.chat_item_right, parent, false);
}
}
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
textChat = (TextView) row.findViewById(R.id.textMessage);
thumbPhoto = (ImageView) row.findViewById(R.id.thumbPhoto);
// Here, just set the text
textChat.setText(chat.mText);
return row;
}
要指示视图回收以提供一致的视图,请添加到适配器:
@Override
public int getItemViewType(int position) {
ChatString chat = getItem(position);
if (chat.mLeft) {
return 0;
} else {
return 1;
}
}
和
@Override
public int getViewTypeCount() {
return 2;
}