2016-11-22 42 views
0

我試圖創建一個自定義視圖,以取代一個xml /膨脹有一定佈局,包含多個預定義的LinearLayout和添加這些看法到每一個預定義的佈局。添加在RelativeLayout的意見,不同的佈局,膨脹

我的預定義佈局包含內部的RelativeLayout作爲親和充氣此xml類4個linearlayouts那裏延伸的RelativeLayout並如下初始化視圖。

private void initView(Context context) { 
    //Inflate and attach your child XML 
    View.inflate(context, R.layout.layout_empty_views, this); 
    llTop = (LinearLayout) findViewById(R.id.linearLayout); 
    llLeft = (LinearLayout) findViewById(R.id.linearLayout2); 
    llBottom = (LinearLayout) findViewById(R.id.linearLayout3); 
    llRight = (LinearLayout) findViewById(R.id.linearLayout4); 
} 

現在,我接受12個子視圖,需要添加3個孩子到每個linearlayout是我現在卡在哪裏。在addView函數中由於索引而不能分割視圖總是-1。

@Override 
public void addView(View child, int index, ViewGroup.LayoutParams params) { 
    if (llTop == null) { 
     super.addView(child, index, params); 
    } else { 
     //Forward these calls to the content view 
     llTop.addView(child, index, params); 
    } 
} 

在onLayout函數中,由於膨脹我的預定義佈局,getChildCount被提高超過12。

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    //super.onLayout(changed, l, t, r, b); 
    // TODO Auto-generated method stub 

    Log.v("Count::", String.valueOf(getChildCount())); 
    /*for (int i = 0; i < getChildCount(); i++) { 
     View v = getChildAt(i); 
     removeViewAt(i); 
     //llTop.addView(v); 
     if (i < 3) { 
      llTop.addView(v); 
     } else if (i > 2 && i < 6) { 
      llRight.addView(v); 
     } else if (i > 5 && i < 9) { 
      llBottom.addView(v); 
     } else if (i > 9) { 
      llLeft.addView(v); 
     } 
    }*/ 
} 

回答

0

addView(View child, int index)接收的索引-1,這意味着它應該被添加到的ViewGroup的末尾。

我不知道我究竟瞭解你的意圖與此視圖,您可能不會在這裏需要自定義視圖。但是,我可以告訴你,你不應該在onLayout函數中添加視圖。這個函數是View的大小和位置的子元素。

退房的Android開發者對creating custom views指南。

+0

是的,但我怎麼動這個觀點到另一個佈局 – chiru