空指针异常 - findViewById()任何人都可以帮我找出这个程序可能存在的问题。在该onCreate()方法中,findViewById()对所有id返回null,这会在以后导致空指针异常。我无法弄清楚为什么findViewById()找不到这个视图。有什么建议?这是主要代码:public class MainActivity extends Activity {
ViewPager pager;
MyPagerAdapter adapter;
LinearLayout layout1, layout2, layout3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout1 = (LinearLayout) findViewById(R.id.first_View);
layout2 = (LinearLayout) findViewById(R.id.second_View);
layout3 = (LinearLayout) findViewById(R.id.third_View);
adapter = new MyPagerAdapter();
pager = (ViewPager) findViewById(R.id.main_pager);
pager.setAdapter(adapter);
}
private class MyPagerAdapter extends PagerAdapter
{
@Override
public int getCount() {
return 3;
}
@Override
public Object instantiateItem(ViewGroup collection, int position) {
LinearLayout l = null;
if (position == 0 )
{
l = layout1;
}
if (position == 1)
{
l = layout2;
}
if (position == 2)
{
l = layout3;
}
collection.addView(l, position);
return l;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view==object);
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
}}
4 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
findViewById()
返回一个View,如果它在你提供的布局中存在setContentView()
,否则返回null,这就是你发生的事情。
示例如果你setContentView(R.layout.activity_first);
然后调用findViewById(R.id.first_View);
它将返回一个View,这是你的布局。
但是如果你调用findViewById(R.id.second_View);
它会返回,null
因为你的activity_first.xml
布局中没有一个视图被调用@+id/second_View
。
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
您尝试获取的视图未在activity_main
布局中定义。您需要以编程方式夸大您尝试添加到寻呼机的视图.-
@Overridepublic Object instantiateItem(ViewGroup collection, int position) { LinearLayout l = null; if (position == 0) { l = (LinearLayout) View.inflate(this, R.layout.activity_first, null); } if (position == 1) { l = (LinearLayout) View.inflate(this, R.layout.activity_second, null); } if (position == 2) { l = (LinearLayout) View.inflate(this, R.layout.activity_third, null); } collection.addView(l, position); return l;}
添加回答
举报
0/150
提交
取消