Android 自定义操作栏/工具栏/标签栏

Posted

技术标签:

【中文标题】Android 自定义操作栏/工具栏/标签栏【英文标题】:Android Custom Action Bar / Tool Bar / Tab Bar 【发布时间】:2021-12-13 15:20:13 【问题描述】:

我能够获得自定义导航 Got the custom navigation correctly 使用以下链接: https://thedeveloperworldisyours.com/android/put-image-navigation-drawer/#sthash.2ThTJIlx.dpbs

接下来我需要用这个What I needed 代替操作栏。但我无法更改此what I got。

我的布局代码:

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_
    android:layout_
    tools:context=".DashboardActivity">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_
        android:layout_ >
    </FrameLayout>

    <LinearLayout
        android:id="@+id/left_drawer"
        android:layout_
        android:layout_
        android:background="@color/white"
        android:layout_gravity="start"
        android:orientation="vertical" >
        <ImageButton
            android:id="@+id/navigation_imageButton1"
            android:layout_
            android:layout_
            android:background="@color/white"
            android:minHeight="48dp"
            android:layout_gravity="end"
            app:srcCompat="@android:drawable/ic_menu_close_clear_cancel" />
        <ImageView
            android:id="@+id/navigation_logo"
            android:layout_
            android:layout_
            android:layout_gravity="center_horizontal"
            android:src="@drawable/dummy_logo" />
        <TextView
            android:id="@+id/navigationAppName"
            android:layout_
            android:layout_
            android:layout_gravity="center_horizontal"
            android:text="@string/app_name"
            android:textSize="30sp"
            android:textStyle="bold" />
        <ListView
            android:id="@+id/list_view_drawer"
            android:layout_
            android:layout_
            android:choiceMode="singleChoice"
            android:layout_marginTop="30dp"
            android:divider="@android:color/darker_gray"
            android:dividerHeight="1dp" />
        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="vertical"
            android:gravity="bottom">

            <TextView
                android:id="@+id/navigation_textView1"
                android:layout_
                android:layout_
                android:textAlignment="center"
                android:textSize="20sp"
                android:text="@string/navigation_text1" />

            <TextView
                android:id="@+id/navigation_textView2"
                android:layout_
                android:layout_
                android:layout_marginBottom="30dp"
                android:textSize="15sp"
                android:textAlignment="center"
                android:text="@string/navigation_text2" />
        </LinearLayout>
    </LinearLayout>

</androidx.drawerlayout.widget.DrawerLayout>

我的 Java 文件的代码:

package com.infiso.healthapp;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.infiso.healthapp.adapter.DrawerItemCustomAdapter;
import com.infiso.healthapp.fragment.AboutFragment;
import com.infiso.healthapp.fragment.DashboardFragment;
import com.infiso.healthapp.fragment.MyCircleFragment;
import com.infiso.healthapp.fragment.ProfileFragment;
import com.infiso.healthapp.model.NavigationDataModel;

public class DashboardActivity extends AppCompatActivity 
    private String[] mOptionMenu;
    private DrawerLayout mDrawerLayout;
    private LinearLayout mDrawerLinearLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mTitleSection;
    private Fragment mFragment = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        mOptionMenu = new String[]  getString(R.string.dashboard_fragment),
                getString(R.string.profile_fragment),
                getString(R.string.myCircle_fragment),
                getString(R.string.about_fragment);
        NavigationDataModel[] drawerItem = new NavigationDataModel[4];

        drawerItem[0] = new NavigationDataModel(android.R.drawable.star_on, getString(R.string.dashboard_fragment),R.drawable.ic_baseline_arrow_forward_ios_24);
        drawerItem[1] = new NavigationDataModel(android.R.drawable.star_on, getString(R.string.profile_fragment),R.drawable.ic_baseline_arrow_forward_ios_24);
        drawerItem[2] = new NavigationDataModel(android.R.drawable.star_on, getString(R.string.myCircle_fragment),R.drawable.ic_baseline_arrow_forward_ios_24);
        drawerItem[3] = new NavigationDataModel(android.R.drawable.star_on,getString(R.string.about_fragment),R.drawable.ic_baseline_arrow_forward_ios_24);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLinearLayout = (LinearLayout) findViewById(R.id.left_drawer);
        mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
        /*mDrawerList.setAdapter(new ArrayAdapter<>(getSupportActionBar()
                .getThemedContext(), R.layout.navigation_listview_item,
                mOptionMenu));*/
        DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.navigation_listview_item, drawerItem);
        mDrawerList.setAdapter(adapter);
        initContentWithFirstFragment();

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 

                switch (position) 
                    case 0:
                        mFragment = new ProfileFragment();
                        break;
                    case 1:
                        mFragment = new DashboardFragment();
                        break;
                    case 2:
                        mFragment = new MyCircleFragment();
                        break;
                    case 3:
                        mFragment = new AboutFragment();
                        break;
                

                FragmentManager fragmentManager = getSupportFragmentManager();

                fragmentManager.beginTransaction()
                        .replace(R.id.content_frame, mFragment).commit();

                mDrawerList.setItemChecked(position, true);

                mTitleSection = mOptionMenu[position];
                getSupportActionBar().setTitle(mTitleSection);

                mDrawerLayout.closeDrawer(mDrawerLinearLayout);
            
        );
        mDrawerList.setItemChecked(0, true);
        mTitleSection = getString(R.string.dashboard_fragment);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close)

            public void onDrawerClosed(View view) 
                getSupportActionBar().setTitle(mTitleSection);
                ActivityCompat.invalidateOptionsMenu(DashboardActivity.this);
            

            public void onDrawerOpened(View drawerView) 
                getSupportActionBar().setTitle(R.string.app_name);
                ActivityCompat.invalidateOptionsMenu(DashboardActivity.this);
            
        ;

        mDrawerLayout.addDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 

        if (mDrawerToggle.onOptionsItemSelected(item)) 
            return true;
        

        switch (item.getItemId()) 
            case R.id.action_settings:
                Toast.makeText(this, R.string.action_settings, Toast.LENGTH_SHORT)
                        .show();
                ;
                break;
            default:
                return super.onOptionsItemSelected(item);
        

        return true;
    

    @Override
    protected void onPostCreate(Bundle savedInstanceState) 
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    

    @Override
    public void onConfigurationChanged(Configuration newConfig) 
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    

    public void initContentWithFirstFragment()

        mTitleSection =getString(R.string.dashboard_fragment);
        getSupportActionBar().setTitle(mTitleSection);
        mFragment = new DashboardFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();

        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, mFragment).commit();
    


适配器代码:

package com.infiso.healthapp.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.infiso.healthapp.R;
import com.infiso.healthapp.model.NavigationDataModel;

public class DrawerItemCustomAdapter extends ArrayAdapter<NavigationDataModel> 

    Context mContext;
    int layoutResourceId;
    NavigationDataModel data[] = null;

    public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, NavigationDataModel[] data) 

        super(mContext, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.data = data;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 

        View listItem = convertView;

        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        listItem = inflater.inflate(layoutResourceId, parent, false);

        ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon);
        TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName);
        ImageView imageViewIcon2 = (ImageView) listItem.findViewById(R.id.imageViewIcon2);

        NavigationDataModel folder = data[position];

        imageViewIcon.setImageResource(folder.icon);
        textViewName.setText(folder.name);
        imageViewIcon2.setImageResource(folder.icon2);
        return listItem;
    

型号代码:

package com.infiso.healthapp.model;

public class NavigationDataModel 

    public int icon;
    public String name;
    public int icon2;

    // Constructor.
    public NavigationDataModel(int icon, String name,int icon2) 

        this.icon = icon;
        this.name = name;
        this.icon2 = icon2;
    

列表视图项的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imageViewIcon"
        android:layout_
        android:layout_
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/textViewName"
        android:layout_
        android:layout_
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/imageViewIcon"
        android:paddingRight="10dp"
        android:text="Item Name"
        android:textColor="@android:color/black"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        />
    <ImageView
        android:id="@+id/imageViewIcon2"
        android:layout_
        android:layout_
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:paddingRight="10dp" />

</RelativeLayout>

风格代码:

<resources xmlns:tools="http://schemas.android.com/tools">

    <style name="Theme.HealthApp" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <item name="android:statusBarColor" tools:targetApi="l">#2fad9a</item>
        <item name="colorPrimary">#2fad9a</item>
        <item name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
    </style>

    <style name="Theme.HealthApp.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="Theme.HealthApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="Theme.HealthApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppBottomSheetDialogTheme"
        parent="Theme.Design.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/AppModalStyle</item>
    </style>

    <style name="AppModalStyle"
        parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@drawable/rounded_bottomsheet_dialog</item>
    </style>
</resources>

AndroidManifest 代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.infiso.healthapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.HealthApp">
        <activity
            android:name=".DashboardActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ForgotPasswordActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".SignupActivity2"
            android:screenOrientation="portrait" />
        <activity
            android:name=".SignupActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".SigninActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".WelcomeActivity"
            android:screenOrientation="portrait">

        </activity>
    </application>

</manifest>

更新版面设计:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_
    android:layout_
    tools:context=".DashboardActivity">
    <com.google.android.material.appbar.AppBarLayout
        android:layout_
        android:layout_>
        <include layout="@layout/custom_action_bar"></include>
    </com.google.android.material.appbar.AppBarLayout>
<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_
    android:layout_>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_
        android:layout_ >
    </FrameLayout>

    <LinearLayout
        android:id="@+id/left_drawer"
        android:layout_
        android:layout_
        android:background="@color/white"
        android:layout_gravity="start"
        android:orientation="vertical" >
        <ImageButton
            android:id="@+id/navigation_imageButton1"
            android:layout_
            android:layout_
            android:background="@color/white"
            android:minHeight="48dp"
            android:layout_gravity="end"
            app:srcCompat="@android:drawable/ic_menu_close_clear_cancel" />
        <ImageView
            android:id="@+id/navigation_logo"
            android:layout_
            android:layout_
            android:layout_gravity="center_horizontal"
            android:src="@drawable/dummy_logo" />
        <TextView
            android:id="@+id/navigationAppName"
            android:layout_
            android:layout_
            android:layout_gravity="center_horizontal"
            android:text="@string/app_name"
            android:textSize="30sp"
            android:textStyle="bold" />
        <ListView
            android:id="@+id/list_view_drawer"
            android:layout_
            android:layout_
            android:choiceMode="singleChoice"
            android:layout_marginTop="30dp"
            android:divider="@android:color/darker_gray"
            android:dividerHeight="1dp" />
        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="vertical"
            android:gravity="bottom">

            <TextView
                android:id="@+id/navigation_textView1"
                android:layout_
                android:layout_
                android:textAlignment="center"
                android:textSize="20sp"
                android:text="@string/navigation_text1" />

            <TextView
                android:id="@+id/navigation_textView2"
                android:layout_
                android:layout_
                android:layout_marginBottom="30dp"
                android:textSize="15sp"
                android:textAlignment="center"
                android:text="@string/navigation_text2" />
        </LinearLayout>
    </LinearLayout>

</androidx.drawerlayout.widget.DrawerLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

自定义应用栏 - 列表视图导航工作正常

但加载 Fragment 的 Frame Layout 不可见

【问题讨论】:

请分享样式和清单文件。 Nadim.. 请立即检查...我在此处添加了样式和 AndroidManifest 文件信息.. 添加了答案。请检查一下 【参考方案1】:

对你的风格做些小改变。

<style name="Theme.HealthApp" 
 parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:statusBarColor" tools:targetApi="l">#2fad9a</item>
    <item name="colorPrimary">#2fad9a</item>
    <item 
name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
</style>

【讨论】:

"NullPointerException" 被抛出,因为没有操作栏.. 在哪一行和哪个文件上? 在 DashboardActivity 文件中,getSupportActionBar().setTitle(mTitleSection);行 评论它。从我的代码中,您可以隐藏默认操作栏,以便您可以绘制自定义操作栏。所以评论吧。 好的,我现在就去看看 Nadim.. 非常感谢!【参考方案2】:

将您的样式 DarkActionBar 更改为 NoActionBar

发件人:

    <style name="Theme.HealthApp" 
 parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:statusBarColor" tools:targetApi="l">#2fad9a</item>
    <item name="colorPrimary">#2fad9a</item>
    <item 
name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
</style>

收件人:

<style name="Theme.HealthApp" 
 parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:statusBarColor" tools:targetApi="l">#2fad9a</item>
    <item name="colorPrimary">#2fad9a</item>
    <item 
name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
</style>

【讨论】:

以上是关于Android 自定义操作栏/工具栏/标签栏的主要内容,如果未能解决你的问题,请参考以下文章

如何在Android中将操作栏标签中心对齐?

ecshop按自定义导航栏上面的标签最下面的一排文章标签不居中 偏左

Android 隐藏状态栏、标题栏、透明状态栏的几种方式

标签视图中的 Android 操作栏搜索

android 中都有哪些不同的栏(状态栏、操作栏、导航栏、工具栏等)?

如何禁用 Sierra 应用程序中的“显示标签栏”菜单选项?