【发布时间】:2011-07-07 19:03:16
【问题描述】:
有没有办法获取LinearLayout的子元素?我的代码返回一个视图(线性布局),但我需要访问布局内的特定元素。
有什么建议吗?
(是的,我知道我可以使用 findViewById,但我是在 java 中创建布局/子项 - 而不是 XML。)
【问题讨论】:
标签: java android android-linearlayout
有没有办法获取LinearLayout的子元素?我的代码返回一个视图(线性布局),但我需要访问布局内的特定元素。
有什么建议吗?
(是的,我知道我可以使用 findViewById,但我是在 java 中创建布局/子项 - 而不是 XML。)
【问题讨论】:
标签: java android android-linearlayout
你总是可以这样做:
LinearLayout layout = setupLayout();
int count = layout.getChildCount();
View v = null;
for(int i=0; i<count; i++) {
v = layout.getChildAt(i);
//do something with your child element
}
【讨论】:
TextView tv = (TextView)((LinearLayout )v).getChildAt(0);
我认为这会有所帮助:findViewWithTag()
为添加到布局中的每个视图设置 TAG,然后像使用 ID 一样通过 TAG 获取该视图
【讨论】:
LinearLayout layout = (LinearLayout)findViewById([whatever]);
for(int i=0;i<layout.getChildCount();i++)
{
Button b = (Button)layout.getChildAt(i)
}
如果它们都是按钮,则强制转换为查看和检查类
View v = (View)layout.getChildAt(i);
if (v instanceof Button) {
Button b = (Button) v;
}
【讨论】:
我会避免从视图的子视图中静态抓取元素。它现在可能可以工作,但会使代码难以维护并且容易在未来的版本中被破坏。如上所述,正确的做法是设置标签并通过标签获取视图。
【讨论】:
你可以这样做。
ViewGroup layoutCont= (ViewGroup) findViewById(R.id.linearLayout);
getAllChildElements(layoutCont);
public static final void getAllChildElements(ViewGroup layoutCont) {
if (layoutCont == null) return;
final int mCount = layoutCont.getChildCount();
// Loop through all of the children.
for (int i = 0; i < mCount; ++i) {
final View mChild = layoutCont.getChildAt(i);
if (mChild instanceof ViewGroup) {
// Recursively attempt another ViewGroup.
setAppFont((ViewGroup) mChild, mFont);
} else {
// Set the font if it is a TextView.
}
}
}
【讨论】:
Kotlin 版本的解决方案是:
val layout: LinearLayout = setupLayout()
val count = layout.childCount
var v: View? = null
for (i in 0 until count) {
v = layout.getChildAt(i)
//do something with your child element
}
【讨论】:
其中一种非常直接的方法是使用 id 访问子视图。
view.findViewById(R.id.ID_OF_THE_CHILD_VIEW)
这里的视图是父视图。
所以例如你的子视图是一个imageview,带有id,img_profile,你可以做的是:
ImageView imgProfile = view.findViewById(R.id.img_profile)
【讨论】: