xXJJJasonMokXx
xXJJJasonMokXx

Reputation: 367

Android: reference to view outside fragment | gesture listener in fragments

I have a TextView in a fragment where I want to set different texts when gesture is detected.

@Override
public boolean onTouchEvent(MotionEvent event) {
    this.gestureDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}

The above code is used to listen for gesture, but it can only be used in an Activity class somehow, when I put .onTouchEvent() in a fragment class, it says cannot resolve method. Any idea how I can manipulate a view from outside the fragment or any ways to basically lsiten for gesture like I did in the Activity class??

Upvotes: 0

Views: 687

Answers (2)

RobP
RobP

Reputation: 9522

To new question: The fragment itself does not have an onTouchEvent, but any View does. So override the Fragment's onCreateView to find the TextView in question and add an onTouchEvent to it. Your onCreateView might just called super() or you might do your own calls to an Inflater or whatever, but here's an (untested) sample using super:

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = super(inflater, container, savedInstanceState);
    TextView myTextView = myView.findViewById(R.id.my_text_view);
    myTextView.setOnTouchListener(new TextView.OnTouchListener( 
        // body of listener here...
    );
}

Upvotes: 1

RobP
RobP

Reputation: 9522

It would be far better encapsulation if you didn't have another class dive into your fragment's view and access it. Instead, have your fragment expose a method to do what you want and keep the specific knowledge of what is in your view local to the Fragment. If there is an obstacle to that approach, advise and there's probably a pattern to help you over it.

Upvotes: 1

Related Questions