我知道如何使用view . getrootview()获得根视图。我也能够从一个按钮的onClick事件中获得视图,其中参数是一个视图。但是我如何在活动中获得视图呢?
当前回答
以防有人需要更简单的方法:
下面的代码给出了整个活动的视图:
[View]
要在活动中获取某个视图,例如在活动中获取imageView,只需添加你想要获取的视图的id:
View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1);
希望这对大家有所帮助
其他回答
如果你需要根视图你的活动(所以你可以添加你的内容)使用
findViewById(android.R.id.content).getRootView()
此外,据报道,在某些设备上,你必须使用
getWindow().getDecorView().findViewById(android.R.id.content)
代替。
请注意,正如Booger所报告的,这可能在某些设备上位于导航栏后面(带有返回按钮等)(但在大多数设备上似乎不是这样)。
如果你需要使用setContentView()方法获取你添加到你的活动的视图,然后作为pottedmeat写你可以使用
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
但最好在xml布局中设置id为这个视图,并使用这个id。
这是我用来获得根视图,因为在XML文件中找到了setContentView赋值:
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
在Kotlin中,我们可以做得更短一些:
val rootView = window.decorView.rootView
从当前活动获取根视图。
在我们的活动中,我们可以通过以下方式获得根视图:
ViewGroup rootView = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
or
View rootView = getWindow().getDecorView().getRootView();
如果你在一个活动中,假设只有一个根视图,你可以像这样得到它。
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
然后可以将其强制转换为真正的类
或者你可以用
getWindow().getDecorView();
注意这将包括动作栏视图,你的视图在动作栏视图下面
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件