Jak obsługiwać kliknięcia przycisków za pomocą XML onClick w fragmentach

[[5]} Pre-Honeycomb (Android 3), każda aktywność została zarejestrowana do obsługi kliknięć przycisków za pomocą znacznika onClick w XML układu:

android:onClick="myClickMethod"

Wewnątrz tej metody można użyć view.getId() i instrukcji switch do wykonania logiki przycisku.

[5]}wraz z wprowadzeniem Plastra Miodu rozbijam te działania na fragmenty, które mogą być ponownie użyte w wielu różnych działaniach. Większość zachowania przycisków jest niezależna od aktywności i chciałbym, aby Kod znajdował się wewnątrz Plik Fragments bez przy użyciu starej (pre 1.6) metody rejestracji OnClickListener dla każdego przycisku.
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
    }
});

Problem polega na tym, że gdy mój układ jest napompowany, to nadal aktywność hostingowa odbiera kliknięcia przycisku, a nie poszczególne fragmenty. Czy istnieje dobre podejście do któregokolwiek

  • zarejestrować fragment, aby otrzymywać kliknięcia przycisku?
  • przekazać zdarzenia kliknięcia z aktywności do fragmentu, do którego należą?
Author: DilithiumMatrix, 2011-05-22

19 answers

Możesz to zrobić:

Aktywność:

Fragment someFragment;    

//...onCreate etc instantiating your fragments

public void myClickMethod(View v) {
    someFragment.myClickMethod(v);
}

Fragment:

public void myClickMethod(View v) {
    switch(v.getId()) {
        // Just like you were doing
    }
}    

W odpowiedzi na @Ameen, który chciał mniej sprzężeń, aby fragmenty były wielokrotnego użytku

Interfejs:

public interface XmlClickable {
    void myClickMethod(View v);
}

Aktywność:

XmlClickable someFragment;    

//...onCreate, etc. instantiating your fragments casting to your interface.
public void myClickMethod(View v) {
    someFragment.myClickMethod(v);
}

Fragment:

public class SomeFragment implements XmlClickable {

//...onCreateView, etc.

@Override
public void myClickMethod(View v) {
    switch(v.getId()){
        // Just like you were doing
    }
}    
 175
Author: Blundell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-19 20:12:21

Do obsługi zdarzeń onClick wolę używać następującego rozwiązania. Działa to również na aktywność i fragmenty.

public class StartFragment extends Fragment implements OnClickListener{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_start, container, false);

        Button b = (Button) v.findViewById(R.id.StartButton);
        b.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.StartButton:

            ...

            break;
        }
    }
}
 608
Author: Adorjan Princz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-19 08:00:22

Myślę, że problem polega na tym, że widok jest nadal aktywnością, a nie fragmentem. Fragmenty nie mają własnego niezależnego widoku i są dołączone do widoku działań nadrzędnych. Dlatego zdarzenie kończy się w aktywności, a nie fragmencie. To niefortunne, ale myślę, że będziesz potrzebował kodu, aby to zadziałało.

To, co robiłem podczas konwersji, to po prostu dodanie słuchacza kliknięć, który wywołuje stary program obsługi zdarzeń.

Na przykład:

final Button loginButton = (Button) view.findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View v) {
        onLoginClicked(v);
    }
});
 30
Author: Brill Pappin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-25 20:02:59

Niedawno rozwiązałem ten problem bez konieczności dodawania metody do aktywności kontekstowej lub konieczności implementacji OnClickListener. Nie jestem pewien, czy jest to "poprawne" rozwiązanie, ale działa.

Na podstawie: https://developer.android.com/tools/data-binding/guide.html#binding_events

Można to zrobić za pomocą wiązań danych: wystarczy dodać instancję fragmentu jako zmienną, a następnie połączyć dowolną metodę za pomocą onClick.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.testapp.fragments.CustomFragment">

    <data>
        <variable android:name="fragment" android:type="com.example.testapp.fragments.CustomFragment"/>
    </data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_place_black_24dp"
            android:onClick="@{() -> fragment.buttonClicked()}"/>
    </LinearLayout>
</layout>

A fragment linkujący kod byłby be...

public class CustomFragment extends Fragment {

    ...

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_person_profile, container, false);
        FragmentCustomBinding binding = DataBindingUtil.bind(view);
        binding.setFragment(this);
        return view;
    }

    ...

}
 27
Author: Aldo Canepa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-21 12:33:40

ButterKnife jest prawdopodobnie najlepszym rozwiązaniem problemu bałaganu. Wykorzystuje procesory adnotacji do generowania tzw. kodu kotła" starej metody".

Ale metoda onClick może być nadal używana, z niestandardowym inflatorem.

Jak używać

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup cnt, Bundle state) {
    inflater = FragmentInflatorFactory.inflatorFor(inflater, this);
    return inflater.inflate(R.layout.fragment_main, cnt, false);
}

Realizacja

public class FragmentInflatorFactory implements LayoutInflater.Factory {

    private static final int[] sWantedAttrs = { android.R.attr.onClick };

    private static final Method sOnCreateViewMethod;
    static {
        // We could duplicate its functionallity.. or just ignore its a protected method.
        try {
            Method method = LayoutInflater.class.getDeclaredMethod(
                    "onCreateView", String.class, AttributeSet.class);
            method.setAccessible(true);
            sOnCreateViewMethod = method;
        } catch (NoSuchMethodException e) {
            // Public API: Should not happen.
            throw new RuntimeException(e);
        }
    }

    private final LayoutInflater mInflator;
    private final Object mFragment;

    public FragmentInflatorFactory(LayoutInflater delegate, Object fragment) {
        if (delegate == null || fragment == null) {
            throw new NullPointerException();
        }
        mInflator = delegate;
        mFragment = fragment;
    }

    public static LayoutInflater inflatorFor(LayoutInflater original, Object fragment) {
        LayoutInflater inflator = original.cloneInContext(original.getContext());
        FragmentInflatorFactory factory = new FragmentInflatorFactory(inflator, fragment);
        inflator.setFactory(factory);
        return inflator;
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if ("fragment".equals(name)) {
            // Let the Activity ("private factory") handle it
            return null;
        }

        View view = null;

        if (name.indexOf('.') == -1) {
            try {
                view = (View) sOnCreateViewMethod.invoke(mInflator, name, attrs);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof ClassNotFoundException) {
                    return null;
                }
                throw new RuntimeException(e);
            }
        } else {
            try {
                view = mInflator.createView(name, null, attrs);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }

        TypedArray a = context.obtainStyledAttributes(attrs, sWantedAttrs);
        String methodName = a.getString(0);
        a.recycle();

        if (methodName != null) {
            view.setOnClickListener(new FragmentClickListener(mFragment, methodName));
        }
        return view;
    }

    private static class FragmentClickListener implements OnClickListener {

        private final Object mFragment;
        private final String mMethodName;
        private Method mMethod;

        public FragmentClickListener(Object fragment, String methodName) {
            mFragment = fragment;
            mMethodName = methodName;
        }

        @Override
        public void onClick(View v) {
            if (mMethod == null) {
                Class<?> clazz = mFragment.getClass();
                try {
                    mMethod = clazz.getMethod(mMethodName, View.class);
                } catch (NoSuchMethodException e) {
                    throw new IllegalStateException(
                            "Cannot find public method " + mMethodName + "(View) on "
                                    + clazz + " for onClick");
                }
            }

            try {
                mMethod.invoke(mFragment, v);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            }
        }
    }
}
 6
Author: sergio91pt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-21 17:06:14

Wolałbym raczej korzystać z obsługi kliknięć w kodzie niż używać atrybutu onClick w XML podczas pracy z fragmentami.

Staje się to jeszcze łatwiejsze, gdy migrujesz swoje działania na fragmenty. Możesz po prostu wywołać obsługę kliknięć (wcześniej ustawioną na android:onClick w XML) bezpośrednio z każdego bloku case.

findViewById(R.id.button_login).setOnClickListener(clickListener);
...

OnClickListener clickListener = new OnClickListener() {
    @Override
    public void onClick(final View v) {
        switch(v.getId()) {
           case R.id.button_login:
              // Which is supposed to be called automatically in your
              // activity, which has now changed to a fragment.
              onLoginClick(v);
              break;

           case R.id.button_logout:
              ...
        }
    }
}

Jeśli chodzi o obsługę kliknięć fragmentami, wygląda to dla mnie prościej niż android:onClick.

 6
Author: Ronnie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 20:38:43

To jest inny sposób:

1.Tworzenie bazowego fragmentu w ten sposób:

public abstract class BaseFragment extends Fragment implements OnClickListener

2.Użycie

public class FragmentA extends BaseFragment 

Zamiast

public class FragmentA extends Fragment

3.In Twoja aktywność:

public class MainActivity extends ActionBarActivity implements OnClickListener

I

BaseFragment fragment = new FragmentA;

public void onClick(View v){
    fragment.onClick(v);
}
Mam nadzieję, że to pomoże.
 5
Author: Euporie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-29 01:39:42

W moim przypadku użycia, mam 50 dziwnych obrazów, które musiałem podłączyć do jednej metody onClick. Moim rozwiązaniem jest zapętlenie widoków wewnątrz fragmentu i ustawienie tego samego słuchacza onclick na każdym z nich:

    final View.OnClickListener imageOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chosenImage = ((ImageButton)v).getDrawable();
        }
    };

    ViewGroup root = (ViewGroup) getView().findViewById(R.id.imagesParentView);
    int childViewCount = root.getChildCount();
    for (int i=0; i < childViewCount; i++){
        View image = root.getChildAt(i);
        if (image instanceof ImageButton) {
            ((ImageButton)image).setOnClickListener(imageOnClickListener);
        }
    }
 5
Author: Chris Knight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-25 23:08:17

Jak widzę odpowiedzi są jakoś stare. Niedawno Googlewprowadziło DataBinding, który jest znacznie łatwiejszy w obsłudze onClick lub przypisaniu do twojego xml.

Oto dobry przykład, który możesz zobaczyć, jak sobie z tym poradzić:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="handlers" type="com.example.Handlers"/>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"
           android:onClick="@{user.isFriend ? handlers.onClickFriend : handlers.onClickEnemy}"/>
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.lastName}"
           android:onClick="@{user.isFriend ? handlers.onClickFriend : handlers.onClickEnemy}"/>
   </LinearLayout>
</layout>

Jest też bardzo fajny tutorial o Databindingu, który znajdziesz tutaj .

 3
Author: Amir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-27 18:12:27

Możesz zdefiniować callback jako atrybut układu XML. Artykuł niestandardowe atrybuty XML dla niestandardowych widżetów Android pokaże Ci, jak to zrobić dla niestandardowego widżetu. Podziękowania dla Kevina Diona:)

Sprawdzam, czy Mogę dodać atrybuty styleable do podstawowej klasy Fragment.

Podstawową ideą jest posiadanie tej samej funkcjonalności, którą View implementuje podczas obsługi wywołania zwrotnego onClick.

 2
Author: Nelson Ramirez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-15 08:01:47

Dodając do odpowiedzi Blundella,
Jeśli masz więcej fragmentów, z dużą ilością onClicks:

Aktywność:

Fragment someFragment1 = (Fragment)getFragmentManager().findFragmentByTag("someFragment1 "); 
Fragment someFragment2 = (Fragment)getFragmentManager().findFragmentByTag("someFragment2 "); 
Fragment someFragment3 = (Fragment)getFragmentManager().findFragmentByTag("someFragment3 "); 

...onCreate etc instantiating your fragments

public void myClickMethod(View v){
  if (someFragment1.isVisible()) {
       someFragment1.myClickMethod(v);
  }else if(someFragment2.isVisible()){
       someFragment2.myClickMethod(v);
  }else if(someFragment3.isVisible()){
       someFragment3.myClickMethod(v); 
  }

} 

W Twoim Fragmencie:

  public void myClickMethod(View v){
     switch(v.getid()){
       // Just like you were doing
     }
  } 
 1
Author: amalBit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-15 07:28:14

Jeśli zarejestrujesz się w xml używając android:Onclick="", wywołanie zwrotne zostanie podane do szanowanej aktywności, w której kontekście należy twój fragment (getActivity() ). Jeśli taka metoda nie zostanie znaleziona w aktywności, system wyrzuci wyjątek.

 1
Author: Isham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-19 08:31:02

Warto rozważyć użycie EventBus dla zdarzeń niepowiązanych .. Możesz słuchać wydarzeń bardzo łatwo. Możesz również upewnić się, że zdarzenie jest odbierane w wątku ui (zamiast wywoływać runOnUiThread.. dla siebie na każde wydarzenie)

Https://github.com/greenrobot/EventBus

From Github:

Android zoptymalizowany szyna zdarzeń, która upraszcza komunikację między Działania, fragmenty, wątki, usługi itp. Mniej kodu, lepiej jakość

 1
Author: programmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 12:24:41

Chciałbym dodać do Adjorn Linkz ' S answer .

Jeśli potrzebujesz wielu obsługi, możesz po prostu użyć referencji lambda

void onViewCreated(View view, Bundle savedInstanceState)
{
    view.setOnClickListener(this::handler);
}
void handler(View v)
{
    ...
}

Sztuczka polega na tym, że podpis metody handler pasuje do podpisu View.OnClickListener.onClick. W ten sposób nie będziesz potrzebował interfejsu View.OnClickListener.

Nie będziesz też potrzebował żadnych instrukcji switch.

Niestety, ta metoda jest ograniczona tylko do interfejsów, które wymagają pojedynczej metody lub lambda.
 1
Author: Dragas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:49

Chociaż zauważyłem kilka ładnych odpowiedzi opierających się na powiązaniach danych, nie widziałem żadnego podejścia w pełnym zakresie z tym podejściem-w sensie włączania rozdzielczości fragmentów, pozwalając jednocześnie na definicje układu wolnego od fragmentów w XML-Ach.

Więc zakładając, że powiązanie danych jest włączone, oto ogólne rozwiązanie, które mogę zaproponować; trochę długie, ale zdecydowanie działa (z pewnymi zastrzeżeniami):

Krok 1: Niestandardowa Implementacja OnClick

To uruchomi wyszukiwanie fragmentaryczne poprzez konteksty powiązane z przyciskiem (np. przycisk):


// CustomOnClick.kt

@file:JvmName("CustomOnClick")

package com.example

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import java.lang.reflect.Method

fun onClick(view: View, methodName: String) {
    resolveOnClickInvocation(view, methodName)?.invoke(view)
}

private data class OnClickInvocation(val obj: Any, val method: Method) {
    fun invoke(view: View) {
        method.invoke(obj, view)
    }
}

private fun resolveOnClickInvocation(view: View, methodName: String): OnClickInvocation? =
    searchContexts(view) { context ->
        var invocation: OnClickInvocation? = null
        if (context is Activity) {
            val activity = context as? FragmentActivity
                    ?: throw IllegalStateException("A non-FragmentActivity is not supported (looking up an onClick handler of $view)")

            invocation = getTopFragment(activity)?.let { fragment ->
                resolveInvocation(fragment, methodName)
            }?: resolveInvocation(context, methodName)
        }
        invocation
    }

private fun getTopFragment(activity: FragmentActivity): Fragment? {
    val fragments = activity.supportFragmentManager.fragments
    return if (fragments.isEmpty()) null else fragments.last()
}

private fun resolveInvocation(target: Any, methodName: String): OnClickInvocation? =
    try {
        val method = target.javaClass.getMethod(methodName, View::class.java)
        OnClickInvocation(target, method)
    } catch (e: NoSuchMethodException) {
        null
    }

private fun <T: Any> searchContexts(view: View, matcher: (context: Context) -> T?): T? {
    var context = view.context
    while (context != null && context is ContextWrapper) {
        val result = matcher(context)
        if (result == null) {
            context = context.baseContext
        } else {
            return result
        }
    }
    return null
}

Uwaga: luźno oparty na oryginalnej implementacji Androida (zobacz https://android.googlesource.com/platform/frameworks/base/+/a175a5b/core/java/android/view/View.java#3025)

Krok 2: deklaratywne zastosowanie w plikach układów

Następnie, w powiązaniu z danymi XML ' s:

<layout>
  <data>
     <import type="com.example.CustomOnClick"/>
  </data>

  <Button
    android:onClick='@{(v) -> CustomOnClick.onClick(v, "myClickMethod")}'
  </Button>
</layout>

Caveats

  • zakłada "nowoczesną" FragmentActivity opartą na implementacji
  • Can tylko Metoda wyszukiwania "top-most" (tj. last) fragmentu w stosie (chociaż można naprawić, jeśli zajdzie taka potrzeba)
 1
Author: d4vidi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-02 20:58:50

To działa dla mnie: (Android studio)

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.update_credential, container, false);
        Button bt_login = (Button) rootView.findViewById(R.id.btnSend);

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                System.out.println("Hi its me");


            }// end onClick
        });

        return rootView;

    }// end onCreateView
 0
Author: Vinod Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-26 13:12:04

Najlepsze rozwiązanie IMHO:

We fragmencie:

protected void addClick(int id) {
    try {
        getView().findViewById(id).setOnClickListener(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void onClick(View v) {
    if (v.getId()==R.id.myButton) {
        onMyButtonClick(v);
    }
}

Następnie w Onviewstaterestored fragmentu:

addClick(R.id.myButton);
 0
Author: user4806368,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-19 07:55:50

Twoja aktywność odbiera oddzwanianie tak, jak musi być użyta:

mViewPagerCloth.setOnClickListener((YourActivityName)getActivity());

Jeśli chcesz, aby twój fragment odbierał callback, zrób to:

mViewPagerCloth.setOnClickListener(this);

I zaimplementować onClickListener Interfejs na fragmencie

 0
Author: CrabsStew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-13 05:25:14

Poniższe rozwiązanie może być lepsze do naśladowania. układ jest w fragment_my.xml

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

    <data>
        <variable
            name="listener"
            type="my_package.MyListener" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <Button
            android:id="@+id/moreTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{() -> listener.onClick()}"
            android:text="@string/login"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

I Fragment byłby następujący

class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
                inflater,
                container,
                false
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment
            }.root
    }

    override fun onClick() {
        TODO("Not yet implemented")
    }

}

interface MyListener{
    fun onClick()
}
 0
Author: sadat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-01 06:56:27