汉堡图标在 Android Studio 中不起作用

Posted

技术标签:

【中文标题】汉堡图标在 Android Studio 中不起作用【英文标题】:Hamburger Icon not working in Android Studio 【发布时间】:2021-12-25 21:32:36 【问题描述】:

您好,我从 Github 获得了一个代码,并对其进行了自定义。该应用程序没有任何导航菜单,这就是我尝试自己添加它的原因(我以前从未制作过应用程序,所以请对我好)。因此,我尝试在 Youtube 上遵循有关如何添加导航菜单的教程。我成功地构建了一个,但是当我尝试运行它时,汉堡包图标似乎没有任何作用。我可能在主要活动中搞砸了,但我似乎找不到错误。请建议我。太感谢了!应用程序代码如下。

package com.adityap.flashy_createflashcards

import android.app.Activity
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.MenuItem
import android.view.animation.GridLayoutAnimationController
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.recyclerview.widget.GridLayoutManager
import com.adityap.flashy_createflashcards.R
import kotlinx.android.synthetic.main.activity_main.*
import android.util.Log
import android.widget.Toast
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adityap.flashy_createflashcards.adapters.DeckRecyclerListAdapter
import com.adityap.flashy_createflashcards.database.DatabaseHelper
import com.adityap.flashy_createflashcards.database.DatabaseHelperFactory
import com.adityap.flashy_createflashcards.models.DeckModel
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() 

    lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
    lateinit var databaseHelper: DatabaseHelper
    lateinit var recyclerView: RecyclerView
    private lateinit var viewAdapter: RecyclerView.Adapter<*>
    private lateinit var viewManager: RecyclerView.LayoutManager


    private var swipeBackgroundColor: ColorDrawable = ColorDrawable(Color.parseColor("#d11a2a"))
    private lateinit var deleteIcon: Drawable

    lateinit var mDeckModelList: MutableList<DeckModel>

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        databaseHelper = DatabaseHelperFactory.getDBHelper(this)
        val fab = findViewById<View>(R.id.fab) as FloatingActionButton

        setUpDrawerLayout()


        fab.setOnClickListener 
            startActivityForResult(Intent(this, CreateDeckActivity::class.java), 123)
        

        fun onOptionsItemSelected(item: MenuItem): Boolean 
            if (actionBarDrawerToggle.onOptionsItemSelected(item)) 
                return true
            
            return super.onOptionsItemSelected(item)
        

        mDeckModelList = mutableListOf()
        mDeckModelList.addAll(databaseHelper.readDeck())

        viewManager = LinearLayoutManager(this)
        viewAdapter = DeckRecyclerListAdapter(this, mDeckModelList)

        deleteIcon = ContextCompat.getDrawable(this, R.drawable.ic_baseline_delete_24)!!

        recyclerView = findViewById<RecyclerView>(R.id.recyclerView).apply 
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter
        


/*        mDeckListAdapter = DeckListAdapter(this, mDeckModelList!!)
        listview.adapter = mDeckListAdapter*/
/*        listview.onItemClickListener = OnItemClickListener  _, _, position, _ ->
            val intent = Intent(this, ReviewDeckActivity::class.java)
            intent.putExtra("Deck", mDeckModelList!![position])
            startActivity(intent)
        */
        val itemTouchHelperCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) 
            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean 
                return false
            

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, postiion: Int) 
                (viewAdapter as DeckRecyclerListAdapter).removeItem(viewHolder as DeckRecyclerListAdapter.CardHolder)
            

            override fun onChildDraw(
                    c: Canvas,
                    recyclerView: RecyclerView,
                    viewHolder: RecyclerView.ViewHolder,
                    dX: Float,
                    dY: Float,
                    actionState: Int,
                    isCurrentlyActive: Boolean) 


                val itemView = viewHolder.itemView

                val iconMargin = (itemView.height - deleteIcon.intrinsicHeight) /2
                if(dX>0)
                    swipeBackgroundColor.setBounds(itemView.left,itemView.top,dX.toInt(),itemView.bottom)
                    deleteIcon.setBounds(itemView.left + iconMargin,
                        itemView.top + iconMargin,
                        itemView.left + iconMargin + deleteIcon.intrinsicWidth,
                        itemView.bottom - iconMargin )
                else 
                    swipeBackgroundColor.setBounds(itemView.right + dX.toInt(),itemView.top, itemView.right,itemView.bottom)
                    deleteIcon.setBounds(itemView.right-iconMargin-deleteIcon.intrinsicWidth,
                        itemView.top + iconMargin,
                        itemView.right-iconMargin,
                        itemView.bottom - iconMargin)
                
                swipeBackgroundColor.draw(c)
                c.save()

                if(dX > 0 )
                    c.clipRect(itemView.left,itemView.top, dX.toInt(), itemView.bottom)
                else
                    c.clipRect(itemView.right+dX.toInt(),itemView.top,itemView.right, itemView.bottom)
                deleteIcon.draw(c)

                c.restore()

                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            
        

        val itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
        itemTouchHelper.attachToRecyclerView(recyclerView)


    

    fun setUpDrawerLayout() 
        setSupportActionBar(main_toolbar)
        actionBarDrawerToggle = ActionBarDrawerToggle(this, mainDrawer, R.string.app_name, R.string.app_name)
        actionBarDrawerToggle.syncState()
        navigationView.setNavigationItemSelectedListener 
            val intent = Intent(this, ProfileActivity::class.java)
            startActivity(intent)
            mainDrawer.closeDrawers()
            true
        
    


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) 
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == 123) 
            mDeckModelList.clear()
            mDeckModelList.addAll(databaseHelper.readDeck())
            viewAdapter.notifyDataSetChanged()
        
    

这是我的 activity_main.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:layout_
    android:layout_
    android:id="@+id/mainDrawer"
    android:background="@drawable/gradientbackground"
    tools:context=".MainActivity">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_
    android:layout_
    android:background="@drawable/gradientbackground"
    tools:context="com.adityap.flashy_createflashcards.MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_
        android:layout_
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/main_toolbar"
            style="@style/Widget.MaterialComponents.Toolbar.Primary"
            android:layout_
            android:layout_
            android:background="@color/colorPrimaryButtonBg"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navigationIcon="@drawable/ic_hamburger"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name" />

    </com.google.android.material.appbar.AppBarLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_
        android:layout_
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout"
        app:layout_constraintVertical_bias="0.0" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_
        android:layout_
        android:layout_marginStart="730dp"
        android:layout_marginLeft="730dp"
        android:contentDescription="TODO"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/recyclerView"
        app:layout_constraintStart_toStartOf="parent"
        app:srcCompat="@drawable/ic_add"
        app:useCompatPadding="true" />


    <ImageView
        android:id="@+id/imageView4"
        android:layout_
        android:layout_
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:srcCompat="@drawable/ic_undraw_lost_online_re_upmy" />


</androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView"
        android:layout_gravity="start"
        android:layout_
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer_menu"
        android:layout_>

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

这是我的drawer_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">


    <item android:title="Profile" />
    <item android:title="Follow us" />
    <item android:title="Rate us" />
</menu>

请帮忙,我刚接触 android studio 和 kotlin,非常感谢。

【问题讨论】:

【参考方案1】:

导航菜单应该有这样的菜单项:

<item
    android:id="@+id/home"
    android:checked="true"
    android:icon="@drawable/ic_home"
    android:title="@string/home" />

并在主 Activity 代码中执行此操作:

protected void onCreate(Bundle savedInstanceState) 
   super.onCreate(savedInstanceState);
        
   setContentView(R.layout.activity_main);
        
   Toolbar toolbar = findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);
        
   NavigationView navView = findViewById(R.id.nav_view);
   drawer = findViewById(R.id.drawer);
        
   toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
        
   drawer.addDrawerListener(toggle);
        
   navView.setNavigationItemSelectedListener(this);
    

然后添加这个回调来监听菜单项点击:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) 


最后一部分非常重要:

@Override
protected void onPostCreate(Bundle state) 
   super.onPostCreate(state);
   toggle.syncState();

SO post 除了这个之外很有用。

【讨论】:

以上是关于汉堡图标在 Android Studio 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

推送通知在android studio中不起作用

为啥我的 FileProvider 在 android studio 中不起作用

主题插件在 Android Studio 中不起作用

横向模式在 Android Studio 模拟器中不起作用?

颤振热重新加载在android studio(mac)中不起作用

.beginTransaction().add 在 Android Studio 中不起作用