Android标题栏添加返回按钮

曾经终败给现在 2022-12-27 08:22 329阅读 0赞

1、xml文件布局:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:app="http://schemas.android.com/apk/res-auto"
  3. android:orientation="vertical"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. <!-- 采用灵活性高的Toolbar替换ActionBar -->
  7. <androidx.appcompat.widget.Toolbar
  8. android:id="@+id/tb_register_back"
  9. android:layout_width="match_parent"
  10. android:layout_height="?attr/actionBarSize"
  11. android:background="?attr/colorPrimary"
  12. android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
  13. app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
  14. </LinearLayout>

2、Activity中具体的调用代码:

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_register);
  5. //初始标题栏
  6. Toolbar toolbar= findViewById(R.id.tb_register_back);
  7. setSupportActionBar(toolbar);
  8. //显示返回按钮
  9. ActionBar actionBar = getSupportActionBar();
  10. if (actionBar != null) {
  11. actionBar.setHomeButtonEnabled(true);
  12. actionBar.setDisplayHomeAsUpEnabled(true);
  13. }
  14. }
  15. /**
  16. * 监听标题栏按钮点击事件.
  17. * @param item 按钮
  18. * @return 结果
  19. */
  20. @Override
  21. public boolean onOptionsItemSelected(MenuItem item) {
  22. //返回按钮点击事件
  23. if (item.getItemId() == android.R.id.home) {
  24. finish();
  25. return true;
  26. }
  27. return super.onOptionsItemSelected(item);
  28. }

3、在AndroidManifest.xml中指定anroid:theme=”@style/AppTheme”

4、在res/values/styles.xml中定义AppTheme主题:

  1. <resources>
  2. <!-- Base application theme. -->
  3. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
  4. <!-- Customize your theme here. -->
  5. <item name="colorPrimary">@color/colorPrimary</item>
  6. <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
  7. <item name="colorAccent">@color/colorAccent</item>
  8. </style>
  9. </resources>

#

发表评论

表情:
评论列表 (有 0 条评论,329人围观)

还没有评论,来说两句吧...

相关阅读