ZoranSmederevac
ZoranSmederevac

Reputation: 23

Prevent clicking on a button in an Activity while showing a Fragment

I am having a problem with the interaction between an Activity and a Fragment.

I have a main Activity and an into Activity with layout buttons and text inputs. When I open the Fragment in the main Activity, I can still click on a button in the Activity and open the Fragment again, or enter text in the text inputs.

I've been searching for help two hours, and I haven't found the answer!

This is how I open the Fragment from the Activity:

FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            SignUp fragment = new SignUp();
            fragmentTransaction.add(R.id.fragment_content, fragment);
            fragmentTransaction.commit();

And this is picture: picture

Upvotes: 2

Views: 2469

Answers (2)

Andrew Hossam
Andrew Hossam

Reputation: 398

I have faced the same problem and searched for hours to find a solution or the reason and I find it.

When you add a fragment to an activity, the functionally of the fragment and activity both will respond to the touch on the screen.

If you want to not touch through the fragment simply create an empty setOnTouchListener in the onViewCreated function of the fragment and it is done.

Code in Java

@Override
protected void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);
    view.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            return true;
        }
    });
}

Code in Kotlin

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    view!!.setOnTouchListener { view, motionEvent -> return@setOnTouchListener true }
}

Upvotes: 3

ZoranSmederevac
ZoranSmederevac

Reputation: 23

Thx to all. I found solution like a jjm say:

"It might be more effective to use two fragments, one with the controls that are currently in the activity, and the fragment you currently have. The button in the first fragment can tell the activity to show the second."

I just create new fragment with component of activity and replace fragments. But i still don't understand why we can click button on activity layout through fragment layout? Why is it usefull?

Upvotes: 0

Related Questions