嗨我需要通過複製和粘貼ViewGroup的某種方式獲取ViewGroup的副本,但不是具有完全相同的位置。所以,我想做到這一點,這就是結果:將一個ViewGroup的內容複製到另一個
public void ViewGroupCopy(ViewGroup source,int sourceOffset,ViewGroup destination,int destinationOffset){
for(int i=sourceOffset;i<source.getChildCount();i++){
View view = source.getChildAt(i);
source.removeView(view);
destination.addView(view, destinationOffset+i, view.getLayoutParams());
}
我在這個代碼塊中使用的方法:
Activity host = (Activity) this.getContext();
View contentView = host.findViewById(android.R.id.content).getRootView();
ViewGroup children = (ViewGroup) contentView;
ViewGroup oldChildren = (ViewGroup) contentView;
children.removeAllViews();
children.addView(new Preview(context));
ViewGroupCopy(oldChildren,0,children,1);
爲了您的其他信息,此類擴展視圖。
嗯,當我嘗試使用它時,我在LogCat中獲得了這個。
09-08 16:34:30.212:E/AndroidRuntime(10992):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.worknwalk/com.example.worknwalk.Text}:java.lang .IndexOutOfBoundsException:index = 1 count = 0
有人能幫我嗎?謝謝。
我已經試過了,我得到這個錯誤: 09-08 18:02:04.189:E/AndroidRuntime(702):了java.lang.RuntimeException:無法開始活動ComponentInfo {com.example.worknwalk/com.example.worknwalk.Text}:java.lang.IllegalStateException:指定的子項已經有父項。您必須先調用子對象的父對象的removeView()。 –
然後我建議像view.setParent(null)或使用迭代器而不是for-loop – Kostas
我得到你的想法,但我沒有看到任何這樣的方法,因爲我認爲ViewGroup(LinearLayout)是父。 –