2012-06-11 27 views
2

Java或C#的回答都很好(我們使用MonoDroid的)安卓入門查看添加LayoutInflator

我成功的一個控件添加到LinearLayout中有:

LayoutInflater _inflatorservice = (LayoutInflater)this.GetSystemService(Context.LayoutInflaterService); 
    var viewContainer = _inflatorservice.Inflate(Resource.Layout.ReportItImageButton, myLinearLayout); 

我如何再拿到一個參考到剛剛添加的視圖?我用這種方式添加了許多相同的控件,因此需要將第n個項目添加到佈局中。

+1

((查看)viewContainer)? –

+0

這給了我linearlayout容器,但不是剛剛添加的內容 –

+1

您可以發佈您的ReportItImageButton.xml佈局嗎?如果你從'Inflate'返回'LinearLayout',那可能是你在膨脹... – kabuko

回答

3

這個工作,它得到最新的產品加入假設產品Button型specfied。

LayoutInflater _inflatorservice = (LayoutInflater)this.GetSystemService(
    Context.LayoutInflaterService); 
var layout = _inflatorservice.Inflate(
    Resource.Layout.ReportItImageButton, layoutImages) as LinearLayout; 

if (layout != null) 
{ 
    var b = layout.GetChildAt(layout.ChildCount - 1) as Button; 
    if (b != null) 
    { 
    } 
} 
+0

看起來你的XML文件並不完美。將LinearLayout從中排除會更好。 –

1

還有一個額外的參數。它不會將您的虛擬視圖添加到myLinearLayout,但仍然返回它的View對象。

var viewObj = _inflatorservice.Inflate(
    Resource.Layout.ReportItImageButton, myLinearLayout, false); 

需要注意的是,例如,如果添加了LinearLayout那麼你會得到一個LinearLayout回來。此方法返回您的XML佈局的視圖,因此它可以是任何類型的View

1
View v = myLinearLayout.findViewById(R.id.myViewId) 

myViewId應該是一樣的ID在你ReportItImageButton.xml文件