Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to Detect userInterations in Android fragments?

Could any one help me out with this situation.

I have implemented OnUserInteraction() method for Android Activity it is working fine for me.

But I want it for Fragments too.How can i able call OnUserInteraction() or is there any another way to identify userInteraction with the UI.

like image 546
Hari Enaganti Avatar asked Nov 28 '16 10:11

Hari Enaganti


1 Answers

@Sunil's answer causes java.lang.StackOverflowError so I corrected it. Below code works smoothly

Create a java class in your app named UserInterationListener and put below code there

public interface UserInteractionListener {
    void onUserInteraction();
}

Then create an instance variable in your activity, for this interface as below

private UserInteractionListener userInteractionListener;

Then implement a setter method for this variable, in your activity.

public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
    this.userInteractionListener = userInteractionListener;
}

Now override the onUserInteraction method of your activity and if the listener variable is not null, invoke the interface method.

@Override
public void onUserInteraction() {
    super.onUserInteraction();
    if (userInteractionListener != null)
        userInteractionListener.onUserInteraction();
}

Now, in your fragment class, implement UserInteractionListener as below

public myFragment extends Fragment implements UserInteractionListener

also override interface's method

@Override
public void onUserInteraction(){
//TODO://do your work on user interaction
}

then in your fragment invoke your activity's userinteraction setter method like below

((YourActivity) getActivity()).setUserInteractionListener(this);

this last part is important.

like image 144
Asad35Waheed Avatar answered Sep 24 '22 10:09

Asad35Waheed