具有NullpointerException的SetOnFocusChangeListener

时间:2016-10-29 14:47:58

标签: java android nullpointerexception

我有片段A:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     view = inflater.inflate(R.layout.fragment_main, container, false);
     CustomKeyboard customKeyboard = new CustomKeyBoard(getActivity());

     etAge = (EditText) getActivity().findViewById(R.id.etAge);
     customKeyboard.actionEt(etAge);
     return view;
}

我有B班:

    public class CustomKeyboard {

private Context context;

    public CustomKeyboard (Context context) {
        this.context = context;
    }

    private void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
                public void actionEt(Edittext edittext){
                    editText.setOnFocusChangeListener((view, hasFocus) -> {
                       if(!hasFocus) {
                             hideKeyboard(view);
                        } else {
                          //........
                        }
                    });
                }
    }

例外:
                                                  引起:java.lang.NullPointerException:尝试调用虚方法' void android.widget.EditText.setOnFocusChangeListener(android.view.View $ OnFocusChangeListener)'在null对象引用上

问题的原因是什么?希望得到一些帮助。

编辑: APP现在运行。但是Edittexts不会隐藏。

2 个答案:

答案 0 :(得分:2)

应该是

etAge = (EditText) view.findViewById(R.id.etAge);

如果没有XML,很难判断;为了安全起见,我们将增加额外的条件。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     view = inflater.inflate(R.layout.fragment_main, container, false);

     etAge = (EditText) view.findViewById(R.id.etAge);
     if(etAge != null){
        CustomKeyboard customKeyboard = new CustomKeyBoard(getActivity());
        customKeyboard.actionEt(etAge);
     }
     return view;
}

答案 1 :(得分:1)

您的代码:

etAge = (EditText) getActivity().findViewById(R.id.etAge);

错误是因为它从活动而不是它所在的视图中膨胀。原因与在不同布局中查找视图时获得Nullpointer相当

正确的代码:

etAge = (EditText) view.findViewById(R.id.etAge);

因为它在视图中找到EditText而不是活动(没有定义的视图膨胀)