简体   繁体   中英

Android onTouch animation up onTouch stopped animation back down

I'm trying to make an imageView move up when a button is touched, and when the button is released I would like it to go back down. I'm starting to write some sample code to at least get it to move up, but I'm already getting a null pointer in my onClick. Any ideas?

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity {
    ImageView img_left;
    ImageView img_right;
    Button left;
    Button right;
    TranslateAnimation moveup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        moveup = new TranslateAnimation(0, 0, 0, 300);
        moveup.setDuration(3000);
        moveup.setFillAfter(true);
        left = (Button) findViewById(R.id.left);
        right = (Button) findViewById(R.id.right);

        left.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                img_left.startAnimation(moveup);
            }

        });



    }

You're not initializing your ImageView objects, they're just null references as far as the program is concerned.

You need to do something like:

//initialize the ImageView
img_left = (ImageView)findViewById(R.id.ID of the image view);
//same thing for img_right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM