2012-12-11 37 views
1

我在frameLayout上添加了五個視圖。在Framelayout上重新排列視圖順序android

如何重新安排framelayout的childIndex。

我用下面的代碼:

fromindex = 3; 
toindex = 4; 
View tempFrom = frameLayout.getChildAt(fromindex); 
View tempTo = frameLayout.getChildAt(toindex); 
frameLayout.removeViewAt(fromindex) 
frameLayout.removeViewAt(toindex) 
frameLayout.addView(tempFrom, toindex) 
frameLayout.addView(tempTo,fromindex) 

但其拋出下面的錯誤。

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

如何重新安排framelayout的childindex?

+0

什麼是錯誤? –

回答

4

如何重新安排的FrameLayout的在childIndex。

FrameLayout不必再直接安排其子女的能力,但你可以通過刪除那些孩子們做出來,重新在正確的位置添加。您的代碼不起作用,因爲您以錯誤的順序刪除了視圖,導致視圖仍然附加到父級:

fromindex = 3; 
toindex = 4; 
View tempFrom = frameLayout.getChildAt(fromindex); 
View tempTo = frameLayout.getChildAt(toindex); 
// first remove the view which is above in the parent's stack 
// otherwise, if you remove the other child you'll call the `removeViewAt` 
// method with the wrong index and the view which was supposed to be detached 
// from the parent is still attached to it 
frameLayout.removeViewAt(toindex); 
frameLayout.removeViewAt(fromindex); 
// first add the child which is lower in the hierarchy so you add the views 
// in the correct order 
frameLayout.addView(tempTo,fromindex) 
frameLayout.addView(tempFrom, toindex) 
+0

現在它的工作..謝謝你.. – RVG

+0

這個命令非常有用......謝謝你..//先刪除父視圖上面的視圖 否則,如果你刪除了另一個孩子,你將會調用帶有錯誤索引的'removeViewAt'方法,並且應該與父代分離的視圖仍然附着在它上面 – RVG

+0

@Ganesh有問題嗎? – Luksprog

0

試試這個代碼

frameLayout.removeView(tempFrom) //to remove views 
frameLayout.removeView(tempTo) 
+0

沒有。它不工作.. – RVG

+0

現在嘗試更新代碼。 –

0

不能交換意見,我認爲。您需要定義新的視圖組並向他的父級膨脹並刪除舊視圖組。

View C = findViewById(R.id.C); 
ViewGroup parent = (ViewGroup) C.getParent(); 
int index = parent.indexOfChild(C); 
parent.removeView(C); 
C = getLayoutInflater().inflate(optionId, parent, false); 
parent.addView(C, index); 
+0

C應該是小寫符合java標準 –