您的位置:首页 > 其它

findViewById值为null,报nullpointer错误的问题

2015-05-27 15:36 260 查看
错误:findViewById返回Null,报nullpointer错误

网上搜了下,拾人牙慧,总结原因,一般为3种:

1.在另一个view的元素应该用baseView.findViewById()来拿,


findViewById()是要指定view的,如果在该view下找不到,自然报null。平时注意养成写view.findViewById()的习惯就不容易错了。
2.findViewById在setContentView(R.layout.main);之前.


即在setContentView调用之前,调用了findViewById去找main布局中的界面元素tv,那么所得到的tv一定是null。正确的做法是挪至setContentView方法调用之后即可。

3.clean一下工程,让ID重新生成

View rowview = (View)inflater.inflate(R.layout.rowview, parent, false);

TextView tv_contact_id =(TextView)rowview.findViewById(R.id.tv_contact_id);

TextView tv_contactname =(TextView)rowview.findViewById(R.id.tv_contactname);

这种情况是调用LayoutInflater.inflate将布局xml规定的内容转化为相应的对象。比如有rowview.xml布局文件(比如在自定义Adapter的时候,用作ListView中的一行的内容的布局),假定在自定的Adapter的getView方法中有类似如下的代码:

有时候居然也会发现rowview非空,但tv_contact_id和tv_contactname都是null!仔细看代码,怎么也看不出错误来。到底是什么原因造成的呢?答案是Eclipse造成的,要解决这个问题,需要这个项目clean一次(Project菜单 -> Clean子菜单),这样就OK了。

原因是因为所查找的对象元素不是存放在默认的(res/layout/activity_main.xml)文件中,而是存放在(res/layout/fragment_main.xml)文件中。所以要在fragment_main.xml去找对应的ID才会找到,而新的IDE生成的代码中加载(fragment_main.xml)文件是在一个内部加载的,所以我们可以在内部类加载处来得到相应对象元素的View:

/**

     * A placeholder fragment containing a simple view.

     */

public static class PlaceholderFragment extends Fragment {

    View rootView = null;

        public PlaceholderFragment() {

        }

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container,

                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_main, container, false);

            

            Button button = (Button) rootView.findViewById(R.id.btn_ok);

            String text = "OK\n";

            button.setText(text);

            

            return rootView;

        }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: