How to add buttons toast message "onClick" in fragment

Moataz Mohamed :

I want to show a Toast message when the user clicks on the button.

I tried many Solution but it is not working for me.

Here is the code

Java "AccountFragment"

public class AccountFragment extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_account, container, false);

    // return the view "Layout"
    return rootView;
}

// display message for the user
public void Tosta (View view) {
    Toast.makeText(getActivity() , "There is no need to Login because you are a tester :D" , Toast.LENGTH_LONG).show();
}}

XML "fragment_account" i used onClick

<Button
    android:id="@+id/button_login_google"
    android:layout_width="261dp"
    android:layout_height="50dp"
    android:layout_marginTop="50dp"
    android:background="@drawable/account_view2"
    android:text="Login with Google"
    android:onClick="Tosta"
    android:textColor="#fff"
    android:textSize="18dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView_login" />
Muntasir Aonik :

Check this Out:

     public class AccountFragment extends Fragment {

        Button btn;

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_account, container, false);

           btn = (Button) rootView.findViewById(R.id.button_login_google);
        btn.setOnClickListener(this);
            return rootView;
        }

        // display message for the user
        @Override
        public void onClick(View v) {
            // Toast here
    Toast.makeText(getActivity(),  "toast", Toast.LENGTH_LONG).show();
        }
}

You can also try this out :

btn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {

                    Toast.makeText(getActivity(),  "toast", Toast.LENGTH_LONG).show();

                    }
                });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=388897&siteId=1