如下面代码所示,是活动直接继承Activity时自定义标题栏的代码
MainActivity
MainActivity
package com.ocular.htcvive.uicustomview; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Window; public class MainActivity extends 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); } }
titlebar.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上一步"/> <TextView android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="标题" android:textSize="18sp" android:gravity="center"/> <Button android:id="@+id/back1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下一步" android:textSize="18sp"/> </LinearLayout>
自定义的主题
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="mystyle" parent="android:Theme.Light"> <item name="android:windowTitleSize">45dp</item> </style> </resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ocular.htcvive.uicustomview"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/mystyle"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
实现的结果如下
问:假如活动Activity是继承兼容包的话,该怎么实现上面那种效果。原因是本人把Activity改成AppcompatActivity时,就会报出如下错误
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ocular.htcvive.uicustomview/com.ocular.htcvive.uicustomview.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity
解决方案
40
事件处理放在上方的switch中即可