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

错误: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;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值