如何单击底部栏上的图标

Posted

技术标签:

【中文标题】如何单击底部栏上的图标【英文标题】:How to click icons at Bottom bar 【发布时间】:2021-10-18 12:00:58 【问题描述】:

我有一个由所有屏幕共享的底栏。在底部栏中,包括三个图标 (bottom_nav.xml) 和菜单导航 (botton_menu_nav.xml)。我的菜单导航工作正常,但现在我无法单击底部栏中的所有三个图标。

有人可以告诉我如何在底部栏中的所有三个图标中添加 onClickListener() 吗?

bottom_nav.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/bottom_navigation"
    tools:ignore="HardcodedText">

    <item
        android:id="@+id/home"
        android:icon="@drawable/home"
        android:title="Home"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/Settings"
        android:icon="@drawable/settings"
        android:title="Settings"
        app:showAsAction="always" />
    <item
        android:icon="@drawable/person"
        android:title=""
        app:showAsAction="always" />
</menu>

Main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout_id"
    android:layout_
    android:layout_
    android:background="@color/white"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity"
    tools:openDrawer="start">


    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_
        android:layout_
        android:orientation="vertical">
        <!--the usual bottom navigation bar with
                app:backgroundTint="@android:color/white"
                -->
        <FrameLayout
            android:id="@+id/framelayout_id"
            android:layout_
            android:layout_ />
        <FrameLayout
            android:id="@+id/framelayout_id2"
            android:layout_
            android:layout_ />

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/bottomAppBar"
            android:layout_
            android:layout_
            android:layout_gravity="bottom"
            app:fabAlignmentMode="end"
            app:fabCradleMargin="10dp"
            app:fabCradleRoundedCornerRadius="20dp"
            app:fabCradleVerticalOffset="10dp"
            app:menu="@menu/bottom_nav"
            app:navigationIcon="@drawable/ic_round_menu" />


        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_
            android:layout_
            android:backgroundTint="@color/black"
            android:contentDescription="@string/app_name"
            android:fitsSystemWindows="true"
            app:backgroundTint="@color/black"
            app:layout_anchor="@id/bottomAppBar"
            app:srcCompat="@drawable/add"
            app:tint="@color/white" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>




    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationview_id"
        android:layout_
        android:layout_
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_layout"
        app:menu="@menu/botton_menu_nav" />
    <!-- Container for the rest of the screen - Below the Toolbar
    android:background="@color/colorPrimary"-->


</androidx.drawerlayout.widget.DrawerLayout>

MainActivity.java


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener

    private DrawerLayout drawerLayout;
    private FrameLayout frameLayout;
    private NavigationView navigationView;
    private SwitchCompat darkModeSwitch;
    private BottomAppBar bottombar;
    private long pressedTime;
    public Boolean bPressed;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        drawerLayout = findViewById(R.id.drawer_layout_id);
        bottombar = findViewById(R.id.bottomAppBar);
        frameLayout = findViewById(R.id.framelayout_id);
        navigationView = findViewById(R.id.navigationview_id);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setItemIconTintList(null);
        darkModeSwitch = (SwitchCompat) navigationView.getMenu().findItem(R.id.nav_lock).getActionView();



        initializeDefaultFragment(savedInstanceState, 0);
        setDarkModeSwitchListener();
        toggleDrawer();

    







    /**
     * Checks if the savedInstanceState is null - onCreate() is ran
     * If so, display fragment of navigation drawer menu at position itemIndex and
     * set checked status as true
     *
     * @param savedInstanceState
     * @param itemIndex
     */
    private void initializeDefaultFragment(Bundle savedInstanceState, int itemIndex) 

        if (savedInstanceState == null) 
            MenuItem menuItem = navigationView.getMenu().getItem(itemIndex).setChecked(true);
            onNavigationItemSelected(menuItem);

        
    

    /**
     * Creates an instance of the ActionBarDrawerToggle class:
     * 1) Handles opening and closing the navigation drawer
     * 2) Creates a hamburger icon in the toolbar
     * 3) Attaches listener to open/close drawer on icon clicked and rotates the icon
     */
    private void toggleDrawer() 
        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, bottombar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(drawerToggle);
        drawerToggle.syncState();
    

    @Override
    public void onBackPressed() 
        int count = getSupportFragmentManager().getBackStackEntryCount();
        //Checks if the navigation drawer is open -- If so, close it
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) 
            drawerLayout.closeDrawer(GravityCompat.START);
        
        else  if (count == 0) 
            if (pressedTime + 2000 > System.currentTimeMillis()) 
                super.onBackPressed();
                finish();
             else 
                Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_SHORT).show();
            
            pressedTime = System.currentTimeMillis();
        
        // If drawer is already close -- Do not override original functionality
        else 
            getSupportFragmentManager().popBackStack();
        
    




    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) 
       //
        switch (menuItem.getItemId()) 
            case R.id.home:
                Toast.makeText(this, "Share Pressed" , Toast.LENGTH_SHORT).show();
            case R.id.nav_account:
                getSupportFragmentManager().beginTransaction().replace(R.id.framelayout_id, new Dashboard())
                        .commit();
                closeDrawer();
                 break;
            case R.id.nav_lock:
                Toast.makeText(this, "Share Pressed", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_categoried:
                Toast.makeText(this, "Trash Pressed", Toast.LENGTH_SHORT).show();
                break;

        
        return true;
    


    /**
     * Attach setOnCheckedChangeListener to the dark mode switch
     */
    private void setDarkModeSwitchListener() 
        darkModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
                if (!isChecked) 
                    Toast.makeText(MainActivity.this, "Dark Mode Turn Off", Toast.LENGTH_SHORT).show();
                 else 
                    Toast.makeText(MainActivity.this, "Dark Mode Turn On", Toast.LENGTH_SHORT).show();
                
            
        );
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 

        getMenuInflater().inflate(R.menu.botton_menu_nav, menu);
        return super.onCreateOptionsMenu(menu);
    

    /**
     * Checks if the navigation drawer is open - if so, close it
     */
    private void closeDrawer() 
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) 
            drawerLayout.closeDrawer(GravityCompat.START);
        
    

    /**
     * Iterates through all the items in the navigation menu and deselects them:
     * removes the selection color
     */
    private void deSelectCheckedState() 
        int noOfItems = navigationView.getMenu().size();

        for (int i = 0; i < noOfItems; i++) 
            navigationView.getMenu().getItem(i).setChecked(false);
        
    






【问题讨论】:

我认为你需要setOnTabSelectListener bottombar 【参考方案1】:

您可以使用以下方法设置点击监听器:

navigationview_id.OnNavigationItemSelectedListener  item ->
    when(item.itemId) 
        R.id.home -> 
            // Respond to navigation item 1 click
            true
        
        R.id.Settings -> 
            // Respond to navigation item 2 click
            true
        
        else -> false
    

看看这个web page

【讨论】:

【参考方案2】:

我相信,你应该像这样在你的活动中覆盖onOptionsItemSelected()

override fun onOptionsItemSelected(item: MenuItem): Boolean 
    when (item.itemId) 
        R.id.item1 -> Log.d("MainActivity","item1 is clicked!")
        R.id.item2 -> Log.d("MainActivity","item2 is clicked!")
        R.id.item3 -> Log.d("MainActivity","item3 is clicked!")
    

    return true

【讨论】:

以上是关于如何单击底部栏上的图标的主要内容,如果未能解决你的问题,请参考以下文章

window8底部任务栏不显示怎么办

无法单击 React Native 中底部导航中的图标

当用户在 Qt 应用程序中单击任务栏/停靠图标时获取事件或通知

ios主屏幕重新命名

未创建 Android listview 内容视图

按钮上的切换图标单击反应