分类: 作者同类文章X•android service 一直上传数据 退到后台过几分钟不请求服务器了•has leaked ServiceConnection com.baidu.location.LocationClient that was originally bound here 百度地图•百度地图 setScanSpan 无效•android content activitynotfoundexception service •android 上传图片(压缩) Bitmap 转File更多两个类中都有findViewById()方法,Activity中的findViewById最终是调用View中的findViewById方法,这个可以从源码看出来:[java] view plaincopypublic View findViewById(int id) { return getWindow().findViewById(id);//activity中的方法 } 
Activity是先拿到window对象,之后再拿view对象:
[java] view plaincopypublic View findViewById(int id) { return getDecorView().findViewById(id); // window中的方法 }
最后才是调用View中的方法:
[java] view plaincopypublic final View findViewById(int id) { if (id < 0) { return null; } return findViewTraversal(id); //View中的方法 }
所以,如果在Activity中调用findViewById(int id)的时候,要注意id的来源,如果id不是在当前Activity所在的窗口,拿到的view对象就为空,比如:[java] view plaincopy@Override PRotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View contentView = getLayoutInflater().inflate(R.layout.popup, null); final PopupWindow popup = new PopupWindow(contentView, 280, 360); Button button = (Button) findViewById(R.id.bn); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popup.showAsDropDown(v); } }); Button button2 = (Button) findViewById(R.id.close); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popup.dismiss(); } }); }
上面的R.id.close不是在activity_main.xml里面,而是在popup.xml里面(布局文件略),所以拿到的button2为null,要真想拿到button2对象,不能直接调用activity的findViewById()方法,而是调用view的findViewById()方法,改为这样就可以了:[java] view plaincopyButton button2 = (Button) contentView.findViewById(R.id.close); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popup.dismiss(); } }); 
转载:http://blog.csdn.NET/breezylee2009/article/details/38580991
顶 1 踩 0 上一篇px,dip,dp sp区别下一篇cannot be resolved or is not a field新闻热点
疑难解答