PlayHardGoPro
PlayHardGoPro

Reputation: 2923

Button click listener from inside fragment

I usually have no problem programming the button click event when using activities, but now I'm studying fragments and I can't make the ButtonClick event work.

My code:

public class LoginFragment extends Fragment {

    Button btnCadastrar;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        btnCadastrar = (Button)view.findViewById(R.id.btn_cadastrar);
        btnCadastrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnCadastrar.setBackground(Drawable.createFromPath("#FFFFFF"));
                Toast.makeText( getContext(), "PIMBAAA", Toast.LENGTH_LONG).show();
            }
        });

        return inflater.inflate(R.layout.fragment_login, container, false);
    }
}  

As you can see, I'm inflating fragment_login, which has the button:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradient_1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginEnd="30dp"
        android:layout_marginStart="30dp"
        android:background="@drawable/transp_white_rect"
        android:orientation="vertical"
        android:padding="20dp">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Cadastrar"
            android:id="@+id/btn_cadastrar"
            android:padding="10dp"
            android:textColor="#FFFFFF"
            android:background="@color/light_blue"
            android:layout_gravity="center_horizontal"
        />
    </LinearLayout>
</RelativeLayout>

Besides the fact that nothing happens when I click/press the button, it appears that the button is NOT clickable. I want some help to understand why it's not working and how to fix it.

Upvotes: 0

Views: 165

Answers (1)

Brian Hoang
Brian Hoang

Reputation: 1111

Looking on you Fragment you will see the inflate code called 2 times. It means 2 fragment_login's views was created on your code.

return view

instead of

return inflater.inflate(R.layout.fragment_login, container, false);

because it will return a new object of fragment_login's view

Upvotes: 1

Related Questions