首页 > 解决方案 > 尝试在 Fragment 中实现 OnClick 侦听器

问题描述

我正在尝试在 Fragment 中实现 On Click 侦听器,但它给了我一个错误“尝试调用虚拟方法”我正在使用 try/catch 来抛出异常错误。是否有人可以指导我如何在 Fragment 中实现 onClick 我有不同的方法,但都是徒劳的。在 XML 中尝试了 onClick,尝试了 Fragment 实现 OnClickListener 和 btn.setOnClickListner 但根本没有工作。

    package com.example.finalapp;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.hbb20.CountryCodePicker;

/**
 * A simple {@link Fragment} subclass.
 * Use the  factory method to
 * create an instance of this fragment.
 */
public class buyer_fragment extends Fragment {
    public EditText mFirstname, mLastname, mUsername, mEmail, mPhone;
    public TextInputEditText mPassword;
    public CountryCodePicker ccp;
    public FirebaseAuth mAuth;
    public Button mSignUp;
    public View view;

    public buyer_fragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_buyer_fragment, container, false);
        initViews();


        return view;
    }


    public void login_back(View view) {
        Intent intent = new Intent(getActivity(), login.class);
        startActivity(intent);


    }

    public void initViews() {
        try {
            mFirstname = view.findViewById(R.id.first_name);
            mLastname = view.findViewById(R.id.last_name);
            mUsername = view.findViewById(R.id.user_name);
            mEmail = view.findViewById(R.id.email);
            mPhone = view.findViewById(R.id.phone_number);
            mPassword = view.findViewById(R.id.signup_password);
            ccp = view.findViewById(R.id.ccp);
            mSignUp = (Button) view.findViewById(R.id.signup_btn1);

           mSignUp.setOnClickListener(this::createUser);

        } catch (Exception e) {
            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public void createUser(View view) {
        try {
            String email = mEmail.getText().toString().trim();
            String password = mPassword.getText().toString().trim();
            mAuth = FirebaseAuth.getInstance();
            mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    Toast.makeText(getContext(), "User Created", Toast.LENGTH_LONG).show();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();

                }
            });


        } catch (Exception e) {
            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


}

我在异常中执行此功能时遇到的错误:

Attempt to invoke Virtual Method 'void.android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

标签: javaandroidandroid-fragmentsfragmentonclicklistener

解决方案


我在使用选项卡布局时犯了一个很小的错误,因此我并行打开了 2 个片段,并且在处理第一个片段时我使用了第二个片段的按钮 ID。我知道这是一个愚蠢的错误,但我是 android 开发的新手,所以我认为这是初学者可以预料到的。相同的代码对我有用,我没有使用任何绑定视图,只需更改该 ID 并知道代码对我来说工作正常。


推荐阅读