2015-10-17 75 views
1

我創造,我吹一個新視圖自定義視圖中:如何誇大一個新的視圖,自定義視圖,編程(安卓)

<declare-styleable name="my_view"> 
    <attr format="reference" name="my_layout"/> 
</declare-styleable> 


public class MyCustomView extends FrameLayout { 
    [...] 

    private void initialize(AttributeSet attrs) { 

    int myLayout = attributes.getResourceId(R.styleable.my_layout, -1); 

    attrs.recycle(); 
    inflate(this.getContext(), myLayout, this); 

    [...] 
} 

而且我把這種方式,對XML文件:

view:my_layout="@layout/custom_layout" 

它工作正常!

但我想要的是以編程方式設置此custom_layout,所以我可以放入一個if子句,以在兩個不同的佈局之間進行選擇。

我試圖創建這個定製類中的公共methos:

private myCustomLayout = -1; 

public void setCustomLayout(int id) 
{ 
    this.myCustomLayout = id; 
} 

然後,我改變了這一點:

int myLayout = attributes.getResourceId(R.styleable.my_layout, -1); 

這樣:

int myLayout = myCustomLayout; 

但顯然沒」工作。

有誰知道,我該怎麼做?

+0

你想什麼時候做出決定?在創建視圖時或在任何特定時間? – Abdullah

+0

我想對我的活動類的方法OnCreate()做出這個決定...我想使我在textView上設置文本時的狀態如myText.seText(「text」);但與我的看法...像myCustomView.setLayout(R.layout.myLayout); –

+0

我想我需要創建一個公共方法,在我的自定義視圖類,所以我可以訪問和發送我的具體佈局......但我不知道如何膨脹這個發送的視圖,在initialize()方法內(自定義視圖類) –

回答

0

我認爲你的initialize()將從你的自定義視圖的構造函數中調用。所以誇大其中的觀點並不明智。您可以刪除代碼以從中充氣視圖。

添加按照你CustomView方法:

public void setCustomLayout(int layout) { 
    LayoutInflater inflater = LayoutInflater.from(getContext()); 
    inflater.inflate(layout, this); 
    invalidate(); 
} 

如果您的佈局包含佈局PARAMS那麼這將是罰款,如果沒有,那麼你可能需要添加布局PARAMS而膨脹的佈局。

從適當的角度從您的onCreate()調用上述方法。