我一直在研究在列表活動中顯示供稿的應用程序。 起初,我得到的信息,並解析它,我把它「的FeedType」我已經創建了,有3個字段的數組:位PIC,字符串名稱和查看內容。 內容代表Feed的內容,並且有不同類型的內容。 該數組正在解析過程中初始化。從現有視圖創建和新視圖
我創建了一個XML文件進佈局。 創建一個ImageView,TextView和LinearLayout,它們將使用addView()來包含「內容」。 我創建了一個包裝並創建我的ListAdapter來重用列表中的對象。
我的問題開始時,我試圖使用添加視圖誰已經是其他LinearLayout的孩子,這是因爲當我從數組中檢索內容我退休的引用到現有的視圖,和不是一個新的觀點。
有沒有一種方法來創建從現有視圖中創建新的看法?或者有人得到了其他解決方案?
代碼:
public class FeedType {
private Bitmap profilePicSrc;
private String name;
private View feedContent;
private Context context;
private final String PIC_BASE_SRC = "xxx";
private final String PIC_END_SRC = "xxx";
public FeedType(String contactId, String name, View feedContent, Context context){
try {
this.profilePicSrc = BitmapFactory.decodeStream((InputStream)new URL(PIC_BASE_SRC + contactId.toString() + PIC_END_SRC).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name;
this.context = context;
this.feedContent = feedContent;
}
public String getName(){
return name;
}
public Bitmap getProfilePicture(){
return profilePicSrc;
}
public View getContent(){
return this.feedContent;
}
}
包裝類:
public class FeedWrapper {
private View base;
private ImageView pic = null;
private TextView name = null;
private LinearLayout content = null;
public FeedWrapper(View base) {
this.base = base;
}
public ImageView getProfilePicture() {
if (pic == null) {
pic = (ImageView)base.findViewById(R.id.pic);
}
return(pic);
}
public TextView getName() {
if (name == null) {
name = (TextView)base.findViewById(R.id.name);
}
return(name);
}
public LinearLayout getContent() {
if (content == null) {
content = (LinearLayout)base.findViewById(R.id.content);
}
else content.removeAllViews();
return(content);
}
}
ListAdapter類:
private class FeedListAdapter extends ArrayAdapter<Object> {
public FeedListAdapter() {
super(Feeds.this, R.layout.feed, new Object[feedArrLength]);
}
public View getView(int position, View convertView, ViewGroup parent) {
View feed = convertView;
FeedWrapper wrapper = null;
if (feed == null) {
feed = getLayoutInflater().inflate(R.layout.feed, parent, false);
wrapper = new FeedWrapper(feed);
feed.setTag(wrapper);
}
else {
wrapper = (FeedWrapper)feed.getTag();
}
wrapper.getName().setText(arr.get(position).getName());
wrapper.getProfilePicture().setImageBitmap(arr.get(position).getProfilePicture());
wrapper.getContent().addView(arr.get(position).getContent());
return(feed);
}
}
我知道這是一個有點難以理解,如果您有任何疑問請詢問。
在此先感謝,埃拉德!
你說:「我的問題開始,當我試圖使用添加一個視圖誰已經是其他LinearLayout的孩子」。你有什麼問題?有什麼異常?你能顯示異常日誌嗎? – NOSTRA
是的,我有一個例外: E/AndroidRuntime(376):java.lang.IllegalStateException:指定的孩子已經有一個父。您必須先調用子對象的父對象的removeView()。 – Elad92