Ian Vink
Ian Vink

Reputation: 68740

Android: Getting the View added with LayoutInflator

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.

Upvotes: 2

Views: 5394

Answers (3)

Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23952

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.

Upvotes: 1

Ian Vink
Ian Vink

Reputation: 68740

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)
    {
    }
}

Upvotes: 3

petey
petey

Reputation: 17140

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

myViewId should be the same as the id specfied in your ReportItImageButton.xml file

Upvotes: 1

Related Questions