问题
Java or C# answers are fine (we use MonoDroid)
I successfully add a control to a LinearLayout with:
LayoutInflater _inflatorservice = (LayoutInflater)this.GetSystemService(Context.LayoutInflaterService);
var viewContainer = _inflatorservice.Inflate(Resource.Layout.ReportItImageButton, myLinearLayout);
How do I then get a reference to the view just added? I add many of the same control this way so would need to get the nth item added to the layout.
回答1:
This works, it gets the most recent item added assuming the item is of type Button
.
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)
{
}
}
回答2:
View v = myLinearLayout.findViewById(R.id.myViewId)
myViewId should be the same as the id specfied in your ReportItImageButton.xml file
回答3:
There is an additional parameter. It doesn't add your inflated view to myLinearLayout
, but still returns the View
object of it.
var viewObj = _inflatorservice.Inflate(
Resource.Layout.ReportItImageButton, myLinearLayout, false);
Note that, for example, if you added a LinearLayout
then you'll get a LinearLayout
back. This method returns the root view of your XML layout so it can be any type of View
.
来源:https://stackoverflow.com/questions/10985949/android-getting-the-view-added-with-layoutinflator