在调用 setContentView() 方法后,我应该调用哪个方法来判断一个活动是否有它的 contentView?
this.getWindow().getDecorView().findViewById(android.R.id.content)
或者this.findViewById(android.R.id.content)
或者this.findViewById(android.R.id.content).getRootView()
如果您给布局设置一个ID,您就可以获得该视图的后退功能。
<RelativeLayout
android:id="@+id/my_relative_layout_id"
并且从 findViewById 中调用它...
findViewById
方法需要传入一个布局元素的 ID,用于查找并返回相应的 View 对象。 - trans这个怎么样?
View view = Activity.getCurrentFocus();
currentFocus?.let { ... }
。 - user924您可以尝试使用View.getRootView()
方法。
您还可以覆盖 onContentChanged()
方法,该方法在调用 setContentView()
后被触发。
Kotlin
this.findViewById<View>(android.R.id.content)
.rootView
.setBackgroundColor(ContextCompat.getColor(this, R.color.black))
没有 "isContentViewSet" 方法。您可以在 setContentView 之前将一些虚拟的 requestWindowFeature 调用放入 try/catch 块中,如下所示:
try { requestWindowFeature(Window.FEATURE_CONTEXT_MENU); setContentView(...) } catch (AndroidRuntimeException e) { // do smth or nothing }
如果内容视图已经设置,requestWindowFeature 将抛出异常。
手机xml布局
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="phone"/>
平板电脑 XML 布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="tablet">
...
</RelativeLayout>
然后在你的活动类中调用它:
View viewPager = findViewById(R.id.pager);
Log.d(getClass().getSimpleName(), String.valueOf(viewPager.getTag()));
希望它对你有用。
getWindow().findViewById(android.R.id.content)
:) - Alex LockwoodsetContentView(R.layout.my_view)
从XML安装布局,则会返回该布局的父级。 - Jay Lieske