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.
Solution:
You have to
use the onClick="."" Transfer entry from the layout/fragment.xml
page to the codebehind page in java/project/fragment_page.java and connect it
to an onClicklistener on a resource.
Subject:
View elements
in an Android fragment to respond to the onClickevent, using the
android:onClick="." in the .xml page.
<Switch
android:id="@+id/SwitchAlarm0"
android:layout_row="0"
android:layout_column="0"
android:onClick="SwitchAlarmOnClick"
/>
|
Lösung in der .java Seite des Fragments:
In der Fragment.java Code Seite fügt man über Ctrl+O die
Override Methode onViewCreated ein. Diese Methode wird aufgerufen, sobald die Fragment
als View erstellt ist.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
{
.. …here onClickListener..
|
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.
@Override
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() {
@Override
public void onClick(View view) {
SwitchAlarmOnClick(view);
}
}
);
}
//----</ route
switch events >----
|