[英]Why am I getting a NullPointerException in this project?
现在,这个问题已经病入膏address。 这是我的工作代码:
package edu.wmich.lab4_jjohns1119;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation;
public class MainFragment extends Fragment {
//Declare widget objects
Button btnAnimate;
ImageView imgTween;
Animation tweenAnimation;
//create view
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflater
View rootView = inflater.inflate(R.layout.fragment_main, container,false);
//Button
btnAnimate = (Button)rootView.findViewById(R.id.btnAnimate);
//Image
imgTween = (ImageView)rootView.findViewById(R.id.imgTween);
//Animation Resource
tweenAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.tween1);
//Button listener for animation
btnAnimate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//animate image
imgTween.startAnimation(tweenAnimation);
}
});
//Return view
return rootView;
}
}
它启动,导航,但是动画什么也没做。 我的猜测是代码的顺序是不正确的广告,它在动画之前显示视图。 这是我的tween1.xml:
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http//schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="-45"
android:duration="400"
/>
您的问题在于分配您的tweenAnimation
字段
Animation tweenAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.tween1);
在片段生命周期(创建)中,此时的getActivity()
为null,这将导致loadAnimation
失败或返回null动画。 然后访问它会导致一个NPE(如果loadAnimation
尚未抛出)
将分配tweenAnimation
的位置移动到片段生命周期中活动将存在的点,如onCreate
恩。
Animation tweenAnimation;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreat(savedInstanceState);
tweenAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.tween1);
}
为什么要使用getView()? 将所有作业移到rootView下方并执行以下操作:
btnAnimate = (Button)rootView.findViewById(R.id.btnAnimate);
为了使动画正常工作,请将名称空间声明更改为:
http://schemas.android.com/apk/res/android
(请注意,示例中缺少http后的冒号)
....
问题是您无法在活动完成构建之前调用getView()
或getActivity()
。 因此,您只需要在以后通过覆盖onActivityCreated(...)
方法来调用这些方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.