我应该调用什么方法来知道一个活动是否有它的contentView(一旦方法setContentView()被调用)?
如果你在布局中添加一个ID,你就可以得到视图。
<RelativeLayout
android:id="@+id/my_relative_layout_id"
从findViewById调用它…
没有“isContentViewSet”方法。你可以把一些伪requestWindowFeature调用放到setContentView之前的try/catch块中,像这样:
try { requestWindowFeature(Window.FEATURE_CONTEXT_MENU); setContentView(...) } catch (AndroidRuntimeException e) { // do smth or nothing }
如果已经设置了内容视图,requestWindowFeature将抛出异常。
this.getWindow().getDecorView().findViewById(android.R.id.content)
or
this.findViewById(android.R.id.content)
or
this.findViewById(android.R.id.content).getRootView()
我发现最好的选择和侵入性较小,是在xml中设置一个标记参数,如
电话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"/>
Tablet 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()));
希望这对你有用。
如果您正在使用Kotlin
this.findViewById<View>(android.R.id.content)
.rootView
.setBackgroundColor(ContextCompat.getColor(this, R.color.black))
推荐文章
- 警告: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文件