2013-12-15 127 views
2

我想創建一個自定義視圖(它擴展了RelativeLayout),它包裝了很多其他視圖。 我想在xml佈局文件中創建該子視圖。現在我想知道如何膨脹那個佈局並在我的自定義視圖中使用它。像這樣的東西會很棒(在我的自定義視圖中):自定義視圖:如何設置根佈局

RelativeLayout rootLayout = (RelativeLayout) inflater.inflate(my xml file) 
this.setContenView(rootLayout); 

不幸的是,這隻有在活動中才有可能。有什麼類似的意見?

編輯: 我不想使用View.addView(rootLayout)的原因,添加另一個視圖層次,這是不需要的。

回答

2

你可以嘗試使用<merge>標記爲根您的佈局中的元素,並在您的自定義RelativeLayout中使用this作爲父項,attachToRoot設置爲true。那麼您無需致電addView

下面是一個LinearLayout(頁面底部)的類似示例,應該使用RelativeLayout too

0

在你的看法,你可以從上下文獲得佈局充氣,充氣兒童並將其添加到this(子類的RelativeLayout

final LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
final View child = inflater.inflate(R.layout.custom_layout, this, false); 
// Then add child to this (subclass of RelativeLayout) 
this.addView(child); 

編輯:

上面的代碼演示瞭如何膨脹自定義視圖內的兒童。 This link顯示瞭如何將自定義視圖本身插入到XML佈局中。

1

使用下面

View v =getLayoutInflater().inflate(R.layout.mylayout,null); 
// inflate mylayout.xml with other views 
CustomRelativeLayout cs = new CustomRelativeLayout(this); 
// CustomRelativeLayout is a class that extends RelativeLayout 
cs.addView(v); // add the view to relative layout 
setContentView(cs); // set the custom relative layout to activity 

實施例:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="111dp" 
     android:text="TextView" /> 

</RelativeLayout> 

SView

public class SView extends RelativeLayout { 

    Paint p,paint; 
    public SView(Context context) { 
     super(context); 
     TextView tv = new TextView(context); 
     tv.setText("hello"); 
     this.addView(tv); 
    } 
} 

在MainActivtiy

View v =getLayoutInflater().inflate(R.layout.mylayout,null); 
SView cs = new SView(this); 
cs.addView(v); 
setContentView(cs); 

捕捉

enter image description here

編輯:

如果你想在CustomRelative佈局

膨脹在構造

LayoutInflater inflater = LayoutInflater.from(context); 
View v =inflater.inflate(R.layout.mylayout,null); 
TextView tv = new TextView(context); 
tv.setText("hello"); 
this.addView(tv); 
this.addView(v); 
+0

這樣我會得到一個額外的嵌套層次,這將不需要 - 我將有一個relativeLayout(CS)和一些額外的根佈局(mylayout),這將嵌套。其中之一是無用的。 – stoefln

+0

@stoefln所以我可能誤解了你的問題可以更清楚或發佈一些代碼片段指示你迄今爲止做了什麼。其中之一是沒用的沒有。實際上你可以動態地創建一個textview並添加到自定義的相對佈局,在這種情況下你不需要mylayout – Raghunandan

+0

@stoefln'CustomRelativeLayout cs = new CustomRelativeLayout(this);'現在你可以像TextView tv = new TextView (這個); tv.setText(「hello」);'現在將textview添加到像'cs.addView(tv);'這樣的相對佈局中。'不需要mylayout – Raghunandan

相關問題