setOnClickListener не работает во фрагменте - PullRequest
0 голосов
/ 04 июля 2019

Я пытаюсь установить onclicklistener в своем фрагменте, в который включена пользовательская панель инструментов, а на панели инструментов у меня есть значок колокольчика, который я пытаюсь поставить onclicklistener, но не работает

Это панель инструментов custom_toolbar.xml

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="@string/app_name">

    <RelativeLayout
            android:id="@+id/notification_bell"
            ..>
        <ImageView
               ..>
        <ImageView
                ..>
        <TextView
                ..>
    </RelativeLayout>
</androidx.appcompat.widget.Toolbar>

Это фрагмент.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".landing.ui.fragment.HomeFragment">

    <include android:id="@+id/custom_toolbar"
             layout="@layout/custom_toolbar"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Затем в Fragment.kt

class HomeFragment : Fragment() {

    private fun initbell(notificationCount:Int) {

        custom_toolbar.notification_bell.setOnClickListener {
            Log.e("Fragment","bell clicked")
        }

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        init()
        .........
    }

    private fun init() {
        initComponent()
        ..........
    }

    private fun initComponent() {
        initbell(it)
        ..........
        }

    }

}

Когда прозвенел звонокнажата, я хочу выполнить какое-то действие.В настоящее время я должен иметь возможность отображать журнал.А также я могу получить к нему доступ и изменить его видимость, так что это не проблема инициации

Ответы [ 5 ]

0 голосов
/ 05 июля 2019

Итак, я изучил его и обнаружил небольшую ошибку: мне пришлось использовать AppBar Layout, которая фактически решила проблему, так как фрагмент.xml не смог получить макет панели приложения, поэтому он не распознавал щелчки. После этого он работал как шарм

во фрагменте. Xml

<androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            tools:context=".landing.ui.fragment.HomeFragment">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
             <include 
                android:id="@+id/custom_toolbar"
                layout="@layout/custom_toolbar"/>
    </com.google.android.material.appbar.AppBarLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
0 голосов
/ 04 июля 2019

Если вы хотите, чтобы RelativeLayout обрабатывал щелчок, вы должны добавить к нему атрибут android:clickable:

<RelativeLayout
   android:id="@+id/notification_bell"
   android:clickable="true"
..>

Это потому, что RelativeLayout пропустит событие касания, передаваемое от него, так чтодочерний вид может обработать событие.

0 голосов
/ 04 июля 2019

Попробуйте, добавьте идентификатор на панель инструментов

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/tb_toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="@string/app_name">

<RelativeLayout
    android:id="@+id/notification_bell"
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:background="@color/colorAccent" />

Затем внутри фрагмента

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    (context as AppCompatActivity).setSupportActionBar(tb_toolbar)

    notification_bell.setOnClickListener {
        Toast.makeText(context, "Yeaey", Toast.LENGTH_LONG).show()
    }
}
0 голосов
/ 04 июля 2019

Добавьте идентификатор в тег панели инструментов в xml, а затем в файл kotlin добавьте нижнюю строку в Метод onViewCreated

(контекст как AppCompatActivity) .setSupportActionBar (your_toolbar_id)

    your_toolbar_id.notification_bell.setOnClickListener {
        Log.d("TAG", "Your Log message here")
    }
0 голосов
/ 04 июля 2019

Альтернатива : -

Взять Относительный макет в качестве заголовка в классе фрагмента, как этот

<androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".landing.ui.fragment.HomeFragment">

<RelativeLayout
    android:id="@+id/header_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
   >


    <ImageView
           ..>
    <ImageView
            ..>
    <TextView
            ..>


</RelativeLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

и в fragment классе с onCreate()

header_bar.setOnClickListener {
            Log.e("Fragment","bell clicked")
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...