Skip to content Skip to sidebar Skip to footer

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.o

Solution 1:

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.


Solution 2:

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...
    );
}

Post a Comment for "Android: Reference To View Outside Fragment | Gesture Listener In Fragments"