If you switch from an activity page to a fragment in Android,  some functions cannot be taken over.

First, the android:onClick="."" entry in the xml page is no longer available.

The events of the fragment are always sent to the parent activity first.



You have to use the onClick="."" Transfer entry from the layout/fragment.xml page to the codebehind page in java/project/ and connect it to an onClicklistener on a resource.



View elements in an Android fragment to respond to the onClickevent, using the android:onClick="." in the .xml page.


Android: onClick in Fragment for Multiple Button Views







Lösung in der .java Seite des Fragments:


In der Code Seite fügt man über Ctrl+O die Override Methode onViewCreated ein. Diese Methode wird aufgerufen, sobald die Fragment als View erstellt ist.


public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

.. …here onClickListener..


Android: onClick in Fragment for Multiple Button Views


If you want to capture several views ab, for example, several buttons, all of which should react to the same onClick event, then you can go through the elements in the for-Loop.

In the example here all switch-view elements labeled "SwitchAlarm" are passed through 0 to 6

First, the ID of the Fragment Resource is searched in layouts and then a binding to exactly this resource is created with .setOnClickListener.


public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
//------------< onViewCreated() >------------
super.onViewCreated(view, savedInstanceState);
//< init >
this.fragmentView =  view ;
//</ init >

    //----< route switch events >----
    //*get onClick() evente from multiple views in fragment
for (int iSwitch=0;iSwitch<7;iSwitch++)
int idView=getResources().getIdentifier("SwitchAlarm" + iSwitch,"id", getContext().getPackageName());
View eventView =view.findViewById(idView);
eventView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//----</ route switch events >----



Software Entwicklung Stuttgart NĂ¼rtingen
Suche Projekte C#, WPF, Windows App,ASP.Net, vb.Net, WinForms, SQL Server, Access, Excel