我有一个使用此代码的Nullpointer Exception,之前它已经很清楚了。异常显示在 mainLayout.setOnTouchListener(this),但我不会理解为什么。在另一个活动中更改了一些代码。:
public class Assistantbuilder extends Activity implements OnTouchListener
{
private ViewFlipper flipper = null;
private float fromPosition;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);
mainLayout.setOnTouchListener(this);
flipper = (ViewFlipper) findViewById(R.id.flipper);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int layouts[] = new int[]{ R.layout.dashboard_layout, R.layout.dashboard_layout2, R.layout.dashboard_layout3, R.layout.dashboard_layout4 };
for (int layout : layouts)
flipper.addView(inflater.inflate(layout, null));
Button btndimensions_rafters = (Button) findViewById(R.id.home_btn_dimensions_rafters);
btndimensions_rafters.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.home_btn_dimensions_rafters:
Intent i = new Intent(Assistantbuilder.this,
dimensions_rafters.class);
startActivity(i);
break;
}
}
});
Button btngable_roof = (Button) findViewById(R.id.home_btn_gable_roof);
btngable_roof.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.home_btn_gable_roof:
Intent i = new Intent(Assistantbuilder.this,
GableRoof.class);
startActivity(i);
break;
}
}
});
}
可能在这里有些错误:
public boolean onTouch(View view, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
fromPosition = event.getX();
break;
case MotionEvent.ACTION_UP:
float toPosition = event.getX();
if (fromPosition > toPosition)
{
flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.go_next_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.go_next_out));
flipper.showNext();
}
else if (fromPosition < toPosition)
{
flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.go_prev_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.go_prev_out));
flipper.showPrevious();
}
default:
break;
}
return true;
}
}
非常感谢。
答案 0 :(得分:1)
好吧,如果该行位于您的活动的onCreate
中,this
应始终有效,因此唯一可以为null的其他内容是mainLayout
。您是否更改了XML布局文件?运行时找不到标识为LinearLayout
的{{1}}。