您始终可以使用ViewGroup#getChildAt()
基于索引检索视图。
另外
如果你有这样的布局:
<ScrollView>
<RelativeLayout>
<LinearLayout>
<Button/>
<Button/>
</LinearLayout>
<TextView/>
</RelativeLayout>
</ScrollView>
然后你可以像这样遍历 ViewTree:
FrameLayout content = (FrameLayout) findViewById(android.R.id.content);
ScrollView scrollView = (ScrollView) content.getChildAt(0);
RelativeLayout relativeLayout = (RelativeLayout) scrollView.getChildAt(0);
LinearLayout linearLayout = (LinearLayout) relativeLayout.getChildAt(0);
Button button1 = (Button) linearLayout.getChildAt(0);
Button button2 = (Button) linearLayout.getChildAt(1);
TextView textView = (TextView) relativeLayout.getChildAt(1);
最好的方案是简单地要求布局设计人员将 id 添加到您想要的元素中。