我知道如何使用view . getrootview()获得根视图。我也能够从一个按钮的onClick事件中获得视图,其中参数是一个视图。但是我如何在活动中获得视图呢?
当前回答
对于那些正在使用数据绑定库的人来说,要获得当前活动的根,只需使用:
View rootView = dataBinding.getRoot();
对于Kotlin用户来说,它甚至更简单:
val rootView = dataBinding.root
其他回答
Kotlin扩展解决方案
使用它来简化活动中的访问。然后你可以直接从Activity或Activity中引用rootView。它外面的rootView:
val Activity.rootView get() = window.decorView.rootView
如果你想为Fragments添加相同的一致性,添加:
val Fragment.rootView get() = view?.rootView
我在android 4.0.3中测试了这个功能,只有:
getWindow().getDecorView().getRootView()
给我们同样的观点
anyview.getRootView();
com.android.internal.policy.impl.PhoneWindow$DecorView@#########
and
getWindow().getDecorView().findViewById(android.R.id.content)
给它的孩子
android.widget.FrameLayout@#######
请证实。
在Kotlin中,我们可以做得更短一些:
val rootView = window.decorView.rootView
如果你在一个活动中,假设只有一个根视图,你可以像这样得到它。
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
然后可以将其强制转换为真正的类
或者你可以用
getWindow().getDecorView();
注意这将包括动作栏视图,你的视图在动作栏视图下面
另一个Kotlin扩展解决方案
如果你的activity的视图是在xml中声明的(ex activity_root.xml),打开xml并给根视图分配一个id:
android:id="@+id/root_activity"
现在在你的类中,使用以下方法导入视图:
import kotlinx.android.synthetic.main.activity_root.root_activity
现在可以使用root_activity作为视图。
推荐文章
- 警告: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文件