[英]Getting View from RelativeLayout
以編程方式,我在其中定義了一個RelativeLayout
和TextView
(稱為標題),如下所示:
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);
我打算以后添加更多的textviews
和buttons
。 但是現在,我想將RelativeLayout
“轉換”(我不確定如何將它寫成文字)到View
中,以便將其放入WindowManager
。 我試圖像這樣使用LayoutInflater
但是它不起作用
LayoutInflater layoutInflater =
(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = layoutInflater.inflate(layout, null );
那么目標是通過addView
將myView
放入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.