마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

이미지뷰 상속 애니메이션 NullPointerException..

0 추천

[Ball.java]

public class Ball extends ImageView
{
	Animation animTranslate = AnimationUtils.loadAnimation(getContext(), R.anim.anim_translate);
	ImageView iv = null;
	public Ball(Context context, int n) 
	{	
		super(context);
		animTranslate.setFillAfter(true);
		
		switch(n)
		{
		case 1:
			iv = (ImageView)findViewById(R.id.Red);
			iv.startAnimation(animTranslate);
			break;
		case 2:
			iv = (ImageView)findViewById(R.id.Blue);
			iv.startAnimation(animTranslate);
			break;
		case 3:
			iv = (ImageView)findViewById(R.id.Green);
			iv.startAnimation(animTranslate);
			break;
		case 4:
			iv = (ImageView)findViewById(R.id.Violet);
			iv.startAnimation(animTranslate);
			break;
		}
	}
}

 

[MainActivity.java]

public class MainActivity extends ActionBarActivity {
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        
//        final Animation animTranslate = AnimationUtils.loadAnimation(this, R.anim.anim_translate);
  
        Ball b1 = new Ball(this, 1);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

 

메인액티비티에서 Ball 객체를 선언하는 부분에서 NullPointerException이 납니다..

정확히는 Ball 클래스의 iv.startAnimation 부분에서 NullPointerException이 납니다...

 

저는 이미지뷰를 상속받아서 그 상속받은 객체를 선언할 때마다 제가 원하는 애니메이션을 주고싶은데

자꾸 NullPointerException이 나오네요.. 어떻게 해야하나요..

익명사용자 님이 2015년 2월 24일 질문

1개의 답변

0 추천
생성자 선언이 잘못된 것 같습니다.

View 를 상속받은 클래스는 아래와 같이, 적어도 2개의 생성자를 구현해 주어야 합니다.

public Ball(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
}
    
public Ball(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
}

저렇게 생성자 구현하시고, 현재 1이라고 넘기는 구분값은 다른 메소드를 만들어서 적용해 보세요~

(하지만 ImageView 를 상속받은 클래스 안의 ImageView 멤버가 생각하신 대로 동작할지는 잘 모르겠네요;;)
가랑비 (10,530 포인트) 님이 2015년 2월 24일 답변
답변 감사합니다..
그래도 계속 iv.startAnimation에서 NullPointerException이 뜨네요..
...