【发布时间】:2014-01-25 05:51:30
【问题描述】:
起初我试图重新调整我的 LinearLayout 并以编程方式查看此问题上发布的内容。
Adjusting linear layout programatically
这怎么会引发另一个异常,特别是 IllegalStateException(说“指定的孩子已经有父母”)
我的Adapter出现的错误,具体在这部分(第二个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
}
【问题讨论】:
-
wrapper.addView(thumbPhoto, 0);thumbPhoto 已经有一个父级,因为它在行中。 -
这里要做的是有2种不同的布局,并使用getViewTypeCount和getItemViewType来声明2种不同的类型。
-
@njzk2 你有什么建议?能否提供代码示例?
-
它将告诉视图回收过程仅回收相同视图类型的视图。
标签: android android-layout illegalstateexception