最近在工作中碰到了一个奇葩问题,在一个Activity中仅仅需要标题栏&&一个Fragment.
为了将问题描述的更为详细一些,这里需要引入一些专业一点的知识。
1.在Activity中定义标题栏
- 定义标题栏样式
<style name="style_titlebar_stand" parent="android:Theme.Light">
<item name="android:windowTitleSize">45dp</item>
<item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
</style>
<style name="WindowTitleBackground">
<item name="android:background">@color/green</item>
</style>
<color name="green">#00ff00</color>
- 在AndroidManifest中进行声明
<activity
android:name=".MainActivity"
android:theme="@style/style_titlebar_stand">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
- 在Activity中进行添加
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
}
这样就完成了一个带有自定义标题栏的Activity!
2.碰到的奇葩问题
titlebar.xml布局如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/fl_titlebar"
android:layout_height="match_parent"></FrameLayout>
如果我仅仅需要一个标题栏&&一个Framgent,根本不需要activity_main布局啊!?我想应该可以这么写
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
FrameLayout titlebarLayout=(FrameLayout)findViewById(R.id.fl_titlebar);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new TestFragment()).commit();
}
在titlebarLayout处打一个断点,你就会看到,titlebarLayout是null!!
3.奇葩解决办法
定义activity_main.xml布局文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<merge>
</merge>
然后运行,ok!
结论
在使用自定义标题栏的时候,如果没有setContentView,自定义titlebar中的组件不能在onCreate中获取!