【问题标题】:How to make the Toolbar button clickable?如何使工具栏按钮可点击?
【发布时间】:2021-03-08 08:38:35
【问题描述】:

我在自定义工具栏中有一个汉堡包按钮。当我单击按钮时,我想打开幻灯片菜单。我的项目正在调试,但是当我单击汉堡按钮时,滑动菜单未打开。有什么想法吗?

MainActivity:

       class MainActivity : AppCompatActivity() {
       private lateinit var userPresenter: UserPresenterInterface
       private var drawerLayout: DrawerLayout? = null
       private var toggle: ActionBarDrawerToggle? = null
       private var rightIcon: Toolbar? = null
       private var navigationView: NavigationView? = null


    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    userPresenter = UserPresenter(resources)
    supportActionBar?.elevation = 0f

        rightIcon?.setOnClickListener {

        drawerLayout = findViewById(R.id.drawer)
        rightIcon = findViewById(R.id.right_icon)
        setSupportActionBar(rightIcon)
        toggle = ActionBarDrawerToggle(this, drawerLayout, rightIcon, 
        R.string.open, R.string.close)
        drawerLayout!!.addDrawerListener(toggle!!)
        toggle!!.syncState()

        navigationView = findViewById(R.id.nav_view)
        }

custom_toolbar.xml:

   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:background="@color/white">

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:id="@+id/right_icon"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_baseline_menu_24"
        android:layout_alignParentRight="true" />
      </RelativeLayout>
     </RelativeLayout>

【问题讨论】:

  • 你为什么要为它制作自定义工具栏。您可以将抽屉布局的重力更改为结束,它看起来与问题中的相同。
  • @ADM 我需要像那个位置这样的汉堡菜单。这就是为什么我需要自定义工具栏。
  • 默认情况下图像视图不可点击 - 尝试添加“Clickable=true”,或许也可以添加“Focusable=true”。希望对您有所帮助。
  • @ADM 我不明白如何实现我的代码,你能做到吗*

标签: android kotlin android-toolbar


【解决方案1】:

尝试添加图像点击列表,并像这样显示和隐藏您的抽屉布局

rightIcon.setOnClickListener {
        if (drawerLayout.isOpen) {
            drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            drawerLayout.openDrawer(GravityCompat.START)
        }
    }

【讨论】:

  • tnx 非常适合您的回答,但它不起作用。 :(
  • 好的,我认为您将抽屉设置为从右侧而不是您需要编辑(GravityCompat.START 进入 GravityCompat.END
  • 我有工具:openDrawer="start" ,我用它替换,没有任何改变。
  • 您在单击按钮时会发现所有 ID,而不是它的工作原理,请向我展示特定活动的所有 xml 和代码 \
  • 它只是 xml 你的活动在哪里
【解决方案2】:

默认情况下,图像视图不可点击 - 尝试添加“Clickable=true”,也可以添加“Focusable=true”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多