android - 如何获得 ScrollView 的唯一直系子节点?

标签 android android-fragments scrollview

我的一个 Activity 可能包含不同的 fragment 类。这些 fragment 中的每一个都有一个特定的布局,可以是 LinearLayout、RelativeLayout 或 ScrollView。 在此布局上,我想以编程方式添加一个 View 。问题是,如果布局是 ScrollView,我无法直接向其添加 View (我收到错误 ScrollView can host only one direct child)。然后,如果 fragment 的布局是一个 ScrollView,我想只接受那个直接子级(它是一个 LinearLayout 或一个 RelativeLayout)。

我怎么能接受呢?我尝试了以下代码

ViewGroup fragmentLayout = (ViewGroup)myFragment.getView();
if (fragmentLayout instanceof ScrollView)
    fragmentLayout = (ViewGroup)fragmentLayout.getChildAt(0);

但是返回的 child 不是我要找的。

最佳答案

ScrollView 只能有一个 child 。如果你在你的 ScrollView 中有一个父 View ,比如相对的或线性的,你可以得到你想要的 child :

for(int i=0; i<((ViewGroup)v).getChildCount(); ++i) {
    View nextChild = ((ViewGroup)v).getChildAt(i);
}

其中 v 是父 View

关于android - 如何获得 ScrollView 的唯一直系子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22353170/

相关文章:

ios - 如何将拉动刷新 Controller 添加到 ScrollView ?

swift - 在 SwiftUI ScrollView 中停止垂直滚动

Android tabcontent 包含将内容隐藏在选项卡后面的 ScrollView

java - 使用接口(interface)实现将线程结果返回给Fragment

java - 如何从主 Activity 刷新 Fragment 中的 ListView?

android - 如何在 Activity 中传递 onActivityResult 数据?

Android Studio 谷歌地图 key

android - 在菜单抽屉/滑动菜单中突出显示所选项目

android - SQLite 数据库结合 fragment

android - 强制关闭查看数据库条目 : Android