【问题标题】:Trying to implement OnClick Listener in Fragment [duplicate]尝试在片段中实现 OnClick 侦听器 [重复]
【发布时间】:2021-11-26 09:36:34
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 我在按钮单击侦听器上获得空对象引用。我会查看您给定的链接,然后在检查后更新
  • @Abuzar 而不是您的情况下的方法initViews()。初始化 onCreateView 中的所有视图。我希望它有效。
  • 是的,我试过了,我已经初始化了 onCreateView 中的所有视图,但是应用程序崩溃并且同样的错误再次出现。我在函数中初始化所有这些视图只是为了通过使用 Try/Catch 来避免应用程序崩溃。

标签: java android android-fragments fragment onclicklistener


【解决方案1】:

为什么不使用 ViewBinding 会解除findViewById()的压力

更多信息,您可以查看view binding setup

你也可以查看How to use ViewBinding in Fragment

根据 @VishalBeep,您可以这样做:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
 view = inflater.inflate(R.layout.fragment_buyer_fragment, container, false);
 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);
    
}

【讨论】:

  • 是的,我已经尝试过@VishalBeep 的方法,但这对我同样的错误不起作用
  • @Abuzar 你试过了吗ViewBinding
  • @Abuzar 你能发布你的 XML 代码吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 2013-02-13
    • 1970-01-01
    • 2023-01-05
    • 2014-01-05
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    相关资源
    最近更新 更多