Android: Getting the View added with LayoutInflator

寵の児 提交于 2019-12-11 03:45:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!