简体   繁体   English

从RelativeLayout获取视图

[英]Getting View from RelativeLayout

Programatically I have a RelativeLayout and TextView (called title) within it defined as follows: 以编程方式,我在其中定义了一个RelativeLayoutTextView (称为标题),如下所示:

RelativeLayout layout = new RelativeLayout(this);
final RelativeLayout.LayoutParams parameters_title = 
      new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
                                       RelativeLayout.LayoutParams.WRAP_CONTENT);  
title.setLayoutParams(parameters_title);
layout.addView(title,parameters_title);

I intend to add more textviews and buttons later. 我打算以后添加更多的textviewsbuttons But for now, I want to "convert" (I am not sure how to put it into words) the RelativeLayout into a View in order to put it into WindowManager . 但是现在,我想将RelativeLayout “转换”(我不确定如何将它写成文字)到View中,以便将其放入WindowManager I was trying to use LayoutInflater like this but it wouldn't work 我试图像这样使用LayoutInflater但是它不起作用

LayoutInflater layoutInflater = 
       (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = layoutInflater.inflate(layout, null );

then the goal is to put myView into WindowManger through addView . 那么目标是通过addViewmyView放入WindowManger How can I get a View from my RelativeLayout ? 如何从RelativeLayout获取View

RelativeLayout extends ViewGroup which has the getChildCount() and getChildAt(int index) methods. RelativeLayout扩展了具有getChildCount()getChildAt(int index)方法的ViewGroup So what you could try is : 因此,您可以尝试的是:

 for(int i=0;i<relativeLayout.getChildCount();i++){
       View child=relativeLayout.getChildAt(i);
       //your processing....
  }

you can do this by getChildAt but you will have to keep the position of the view you want to get from layout. 您可以通过getChildAt来做到这一点,但必须保留要从布局中获取的视图的位置。 To avoid this you can set an id for your view and get the view with findViewById(). 为了避免这种情况,您可以为视图设置一个id并使用findViewById()获取视图。 If you inflate a view from xml you will get the same views as xml. 如果从xml扩展视图,则将获得与xml相同的视图。 if you add some new views to the relativeLayout it will not effect the view you inflate from the xml. 如果将一些新视图添加到relativeLayout,则不会影响您从xml扩展的视图。

when you are adding the view: 在添加视图时:

 myView.setId(id);
 layout.addView(myView);

when you are retrieving 当您检索时

 View myView = layout.findViewById(id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM