Android Studio Click a button inside a Fragment

Asked

Viewed 168 times

-1

Hello,

I need to trigger the event click a button that is inside a Fragment.

I was following the answer of this article, but (excuse my ignorance) it was too complicated for me to understand, because the author of the answer says to create this, create that, but does not say where: if inside the Fragment or within the MainActivity or within the Interface itself, at last...

There came a time when I got lost in the explanation.

My project follows the following pattern:

A Main Activity:

<RelativeLayout
...
>
    <LinearLayout
      ...
        >

        <com.google.android.material.tabs.TabLayout
         ...>

            <com.google.android.material.tabs.TabItem
             ... />

            <com.google.android.material.tabs.TabItem
             ... />
        </com.google.android.material.tabs.TabLayout>

        <androidx.viewpager.widget.ViewPager
         ...
            >
        </androidx.viewpager.widget.ViewPager>
    </LinearLayout>

Then inside the Fragment User has a sign up button (btnCadUser).

Well... I created the Interface, I implemented in MainActivity, I created the methods, but I’m not able to create the button click event nor instantiate the EditText from within the Fragment...

Always returns me null reference, for example:

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$Onclicklistener)' on a null Object Reference

Thank you very much to anyone who can explain or who has a step by step, because the videos and articles I have found on the Internet assume that the reader is already a skull in Android development.

1 answer

0


Gentlemen(s)

I solved my question.

What worked for me wasn’t creating Interface, nor Implementing anything, nor creating methods within the Interface. The interface is important, yes, but I didn’t need it in this case.

What I had to do was:

Within the onCreateView of my Fragment (not of Mainactivity):

  • "Inflate" the Fragment as a View;
  • Then declare the objects (button, Edittexts, etc);
  • Then declare the setOnClickListener from my sign-up button;
  • Then return the Fragment, who I called fragmentoUsuario

as shown below: inserir a descrição da imagem aqui

That’s it. I hope it helps others with the same problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.