【问题标题】:Android toolbar back arrow does nothingAndroid 工具栏后退箭头什么都不做
【发布时间】:2022-11-18 19:12:45
【问题描述】:

我不知道为什么我在工具栏上的后退箭头不起作用,任何人都可以帮助我吗?

我将活动的 onCreate、适配器和 xml 留在这里 我使用带有约束布局的 recyclerView

这是活动“onCreate”类的代码:

@Override
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(com.owncloud.android.R.layout.accounts_layout)
    tintedCheck = ContextCompat.getDrawable(this, com.owncloud.android.R.drawable.ic_current_white)!!
    tintedCheck = DrawableCompat.wrap(tintedCheck)
    val tint = ContextCompat.getColor(this, com.owncloud.android.R.color.actionbar_start_color)
    DrawableCompat.setTint(tintedCheck, tint)

    val recyclerView: RecyclerView = findViewById(com.owncloud.android.R.id.account_list_recycler_view)
    recyclerView.run {
        filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(applicationContext)
        adapter = accountListAdapter
        layoutManager = LinearLayoutManager(this@AccountManagementActivity)
    }

    setupStandardToolbar(
        getString(com.owncloud.android.R.string.prefs_manage_accounts),
        displayHomeAsUpEnabled = true,
        homeButtonEnabled = true,
        displayShowTitleEnabled = true
    )

    val accountList = AccountManager.get(this).getAccountsByType(accountType)
    originalAccounts = toAccountNameSet(accountList)
    originalCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(this).name

    accountListAdapter.submitAccountList(accountList = getAccountListItems())

    account = AccountUtils.getCurrentOwnCloudAccount(this)
    onAccountSet(false)

    /**
    // added click listener to switch account
    recyclerView.onItemClickListener = OnItemClickListener { parent, view, position, id ->
    switchAccount(
    position
    )
    }
     */
}

来自 Adapter 的代码,实现了 recyclerView:

class AccountManagementAdapter(private val accountListener: AccountManagementActivity) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var accountItemsList = listOf<AccountRecyclerItem>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)

        return if (viewType == AccountManagementRecyclerItemViewType.ITEM_VIEW_ACCOUNT.ordinal) {
            val view = inflater.inflate(R.layout.account_item, parent, false)
            view.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(parent.context)
            AccountManagementViewHolder(view)
        } else {
            val view = inflater.inflate(R.layout.account_action, parent, false)
            view.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(parent.context)
            NewAccountViewHolder(view)
        }
    }

    fun submitAccountList(accountList: List<AccountRecyclerItem>) {
        accountItemsList = accountList
        notifyDataSetChanged()
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is AccountManagementViewHolder -> {
                val accountItem = getItem(position) as AccountRecyclerItem.AccountItem
                val account: Account = accountItem.account

                try {
                    val oca = OwnCloudAccount(account, holder.itemView.context)
                    holder.binding.name.text = oca.displayName
                } catch (e: Exception) {
                    Timber.w(
                        "Account not found right after being read :\\ ; using account name instead of display " +
                                "name"
                    )
                    holder.binding.name.text = AccountUtils.getUsernameOfAccount(account.name)
                }
                holder.binding.name.tag = account.name

                holder.binding.account.text = DisplayUtils.convertIdn(account.name, false)

                try {
                    val avatarUtils = AvatarUtils()
                    avatarUtils.loadAvatarForAccount(
                        holder.binding.icon,
                        account,
                        true,
                        20f
                    )
                } catch (e: java.lang.Exception) {
                    Timber.e(e, "Error calculating RGB value for account list item.")
                    // use user icon as a fallback
                    holder.binding.icon.setImageResource(R.drawable.ic_user)
                }

                if (AccountUtils.getCurrentOwnCloudAccount(holder.itemView.context).name == account.name) {
                    holder.binding.ticker.visibility = View.VISIBLE
                } else {
                    holder.binding.ticker.visibility = View.INVISIBLE
                }

                /// bind listener to refresh account
                holder.binding.refreshAccountButton.apply {
                    setImageResource(R.drawable.ic_action_refresh)
                    setOnClickListener { accountListener.refreshAccount(account) }
                }

                /// bind listener to change password
                holder.binding.passwordButton.apply {
                    setImageResource(R.drawable.ic_baseline_lock_reset_grey)
                    setOnClickListener { accountListener.changePasswordOfAccount(account) }
                }

                /// bind listener to remove account
                holder.binding.removeButton.apply {
                    setImageResource(R.drawable.ic_action_delete_grey)
                    setOnClickListener { accountListener.removeAccount(account) }
                }

                ///bind listener to switchAccount
                holder.binding.account.apply {
                    setOnClickListener { accountListener.switchAccount(position) }
                }
            }
            is NewAccountViewHolder -> {
                holder.binding.icon.setImageResource(R.drawable.ic_account_plus)
                holder.binding.name.setText(R.string.prefs_add_account)

                // bind action listener
                holder.binding.linearLayout.setOnClickListener {
                    accountListener.createAccount()
                }
            }
        }

    }

    override fun getItemCount(): Int = accountItemsList.size

    fun getItem(position: Int) = accountItemsList[position]

    sealed class AccountRecyclerItem {
        data class AccountItem(val account: Account) : AccountRecyclerItem()
        object NewAccount : AccountRecyclerItem()
    }

    class AccountManagementViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val binding = AccountItemBinding.bind(itemView)
    }

    class NewAccountViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val binding = AccountActionBinding.bind(itemView)
    }

    override fun getItemViewType(position: Int): Int {
        return when (getItem(position)) {
            is AccountRecyclerItem.AccountItem -> AccountManagementRecyclerItemViewType.ITEM_VIEW_ACCOUNT.ordinal
            is AccountRecyclerItem.NewAccount -> AccountManagementRecyclerItemViewType.ITEM_VIEW_ADD.ordinal
        }
    }

    enum class AccountManagementRecyclerItemViewType {
        ITEM_VIEW_ACCOUNT, ITEM_VIEW_ADD
    }

    /**
     * Listener interface for Activities using the [AccountListAdapter]
     */
    interface AccountAdapterListener {
        fun removeAccount(account: Account)
        fun changePasswordOfAccount(account: Account)
        fun refreshAccount(account: Account)
        fun createAccount()
        fun switchAccount(position: Int)
    }
}

最后我给你留下两个 xml 文件,一个声明了所有项目,一个实现了 recyclerView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/accounts_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/owncloud_toolbar" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/account_list_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</LinearLayout>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="?android:attr/selectableItemBackground"
    >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginStart="@dimen/standard_margin"
        android:src="@drawable/ic_account_plus"
        android:background="?android:attr/selectableItemBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/ticker"
        android:layout_width="16dp"
        android:layout_height="16dp"
        android:layout_marginTop="-8dp"
        android:layout_marginEnd="-8dp"
        android:src="@drawable/ic_current"
        app:layout_constraintEnd_toEndOf="@id/icon"
        app:layout_constraintTop_toTopOf="@id/icon" />
    <!-- drawable will be replaced by ic_current_white + tint in runtime;
    ic_current here as a placeholder -->

    <TextView
        android:id="@+id/name"
        android:layout_width="210dp"
        android:layout_height="28dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="4dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:text="@string/placeholder_filename"
        android:textColor="@color/textColor"
        android:textSize="16sp"
        android:textStyle="bold"
        android:background="?android:attr/selectableItemBackground"
        app:layout_constraintEnd_toStartOf="@+id/refreshAccountButton"
        app:layout_constraintStart_toEndOf="@id/ticker"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/account"
        android:layout_width="210dp"
        android:layout_height="44dp"
        android:layout_marginStart="30dp"
        android:layout_marginEnd="@dimen/standard_half_margin"
        android:layout_marginBottom="4dp"
        android:ellipsize="end"
        android:text="@string/placeholder_sentence"
        android:textColor="@color/textColor"
        android:textSize="14sp"
        android:background="?android:attr/selectableItemBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/refreshAccountButton"
        app:layout_constraintStart_toEndOf="@id/ticker"
        app:layout_constraintTop_toBottomOf="@id/name" />

    <ImageView
        android:id="@+id/refreshAccountButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:contentDescription="@string/actionbar_sync"
        android:paddingLeft="@dimen/standard_half_padding"
        android:paddingTop="@dimen/standard_padding"
        android:paddingRight="@dimen/standard_half_padding"
        android:paddingBottom="@dimen/standard_padding"
        android:src="@drawable/ic_action_refresh"
        android:background="?android:attr/selectableItemBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/passwordButton"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tint="@color/black" />

    <ImageView
        android:id="@+id/passwordButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:paddingLeft="@dimen/standard_half_padding"
        android:paddingTop="@dimen/standard_padding"
        android:paddingRight="@dimen/standard_half_padding"
        android:paddingBottom="@dimen/standard_padding"
        android:src="@drawable/ic_baseline_lock_reset_grey"
        android:background="?android:attr/selectableItemBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/removeButton"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tint="@color/black" />

    <ImageView
        android:id="@+id/removeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:paddingStart="@dimen/standard_half_padding"
        android:paddingTop="@dimen/standard_padding"
        android:paddingEnd="@dimen/standard_padding"
        android:paddingBottom="@dimen/standard_padding"
        android:src="@drawable/ic_action_delete_grey"
        android:background="?android:attr/selectableItemBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tint="@color/black" />

</androidx.constraintlayout.widget.ConstraintLayout>

如果需要更多代码,我可以添加它:)

我试着添加这样的东西:

if(item.getItemId() ==android.R.id.home){
  onBackPressed();
}

和这样的事情:

binding.toolbar.setNavigationOnClickListener { navController.popBackStack() }

但没有任何效果

【问题讨论】:

    标签: android kotlin android-recyclerview toolbar android-constraintlayout


    【解决方案1】:

    在您定义 navController 的地方添加以下代码:

        override fun onSupportNavigateUp(): Boolean {
            return NavigationUI.navigateUp(yourNavController, null) || super.onSupportNavigateUp()
        }
    

    【讨论】:

    • 我这里没有导航组件:(
    • 为了控制导航或后退按钮,您需要具有导航组件或手动定义的片段事务。如果你没有这些,后退按钮不知道去哪里,也不起作用。本文档将帮助你link
    【解决方案2】:

    我刚刚解决了在活动类中添加此功能的问题:

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        var retval = true
        when (item.itemId) {
            R.id.home -> onBackPressed()
            else -> retval = super.onOptionsItemSelected(item)
        }
        return retval
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多