线性布局单击片段上的事件时出现NullPointerException

时间:2014-04-30 09:48:22

标签: android

我有一个片段,我想在单击线性布局时显示一个对话框,但是当我尝试找到idioma的LinearLayout时,我得到一个NullPointer异常,这是我的代码,有人可以帮助我吗?谢谢

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {




    View view = inflater.inflate(R.layout.preferencias, container, false);


    LinearLayout idioma_layout= (LinearLayout) getView().findViewById(R.id.idioma_layout);
    idioma_layout.setOnClickListener(new OnClickListener()
    {
     @Override
     public void onClick(View v)
     {

         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.language_prompt);
            builder.setItems(R.array.languages, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    // Do something with the selection
                    switch (item) {
                        case 0:
                         Toast.makeText(getActivity(), "Español", Toast.LENGTH_LONG).show();
                         savePreferences("idioma","es");

                         break;
                        case 1:
                          Toast.makeText(getActivity(), "Inglés", Toast.LENGTH_LONG).show();
                          savePreferences("idioma","en");

                          break;

                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();

     } 
    }); 

    setHasOptionsMenu(true);


    return view;

1 个答案:

答案 0 :(得分:4)

您无法在getView()内使用onCreateView()方法。视图尚未创建,getView()在这种情况下返回null。

您已经必须在此方法中查看(您只是将其虚增为view变量):

View view = inflater.inflate(R.layout.preferencias, container, false);
LinearLayout idioma_layout= (LinearLayout) view.findViewById(R.id.idioma_layout);