簡體   English   中英

從RelativeLayout獲取視圖

[英]Getting View from RelativeLayout

以編程方式,我在其中定義了一個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);

我打算以后添加更多的textviewsbuttons 但是現在,我想將RelativeLayout “轉換”(我不確定如何將它寫成文字)到View中,以便將其放入WindowManager 我試圖像這樣使用LayoutInflater但是它不起作用

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

那么目標是通過addViewmyView放入WindowManger 如何從RelativeLayout獲取View

RelativeLayout擴展了具有getChildCount()getChildAt(int index)方法的ViewGroup 因此,您可以嘗試的是:

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

您可以通過getChildAt來做到這一點,但必須保留要從布局中獲取的視圖的位置。 為了避免這種情況,您可以為視圖設置一個id並使用findViewById()獲取視圖。 如果從xml擴展視圖,則將獲得與xml相同的視圖。 如果將一些新視圖添加到relativeLayout,則不會影響您從xml擴展的視圖。

在添加視圖時:

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

當您檢索時

 View myView = layout.findViewById(id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM